BlogEngine.Net 1.XX where have you gone?

How to convert a DTED (Elevation) File to a Raster

29. September 2010 12:46 by Scott in   //  Tags:   //   Comments (62)

Since I couldn’t find it on the internet, I decided to post it here.

using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesRaster;
 
string dtedFile = @"C:\Examples\DTED Level 2\E35\N82.DT2";
IWorkspaceFactory workspaceFactoryShape = new RasterWorkspaceFactoryClass();
IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactoryShape.OpenFromFile(System.IO.Path.GetDirectoryName(dtedFile), 0);
IRasterDataset ds = rasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(dtedFile));
IRaster raster = ds.CreateDefaultRaster();

A few things to point out:

  1. The OpenFromFile method is only looking for the directory and not actually the file name.  It has to open a workspace before it opens the file.
  2. The OpenRasterDataset method is where you give just the file name of the dted file.  Remember it already has the file path I stated in the first point.

This code took me almost a full day to figure out.  Its not easily findable on the internet.  Hope it helps someone else out there.

Scott

If you liked this post, please be sure to subscribe to my RSS Feed.

Internet Explorer 9 and Their Javascript Problem

19. September 2010 20:52 by Scott in   //  Tags:   //   Comments (3)

I own a website over at http://www.Utopiapimp.com.  I have well over 2 million pageviews daily and most of my users are Firefoxers or Chromers.  But when I run Internet Explorer against my site I receive a few errors.  Even with the brand new Internet Explorer 9 Beta, there is still a Javascript problem.  I use third party tools such as Google Analytics and the Intense Debate comment system.  Each third party tool also employs the same javascript file from Quantserve that I pull for my site.

The problem is this, IE doesn’t just pull one quant.js file for all three times it gets mentioned in my site, It pulls it three times.  Therefore it gets declared three times along with all the global javascript variables. That means I receive errors and can’t run all my javascript code correctly. But what browsers do this correctly?  Chrome and Firefox, and its because of small things like this, why I keep surfing with Firefox and Chrome and just don’t touch IE.

This article was written with specific intent to reach the Internet Explorer Team and hope they make a fix before IE 9 comes out of Beta.

Scott

If you liked this post, please be sure to subscribe to my RSS Feed.

How to Shrink a SQL Transaction Log File

13. September 2010 13:58 by Scott in   //  Tags:   //   Comments (42)

I was having trouble with a transaction log file that had unrestricted growth set.  I needed to get it down to a good size without killing my disk space.  So below is the script I used to shrink the transaction log after it had gone a little wild with size.

backup
log 'yourdatabasename' to disk ='D:\YourdatabaseName.trn'
go
dbcc
shrinkfile (yourdatabase_logfilename,1)
If you liked this post, please be sure to subscribe to my RSS Feed.

The path X is already mapped in workspace Y

31. August 2010 14:42 by Scott in   //  Tags:   //   Comments (14)

When running Team Foundation Server, I ran into a slight problem.  I just finished installing TFS 2010 and while I had old code, I needed to upload that old code to TFS 2010.

So I began the process and to my dismay, the code was already mapped to another directory.  So after searching around, I couldn’t find anything.

So I went looking around. Under this directory, I found a version control file.  After looking at it, I noticed the maps.  So all I did was delete the old server maps in the config file and all seemed to work.

C:\Documents and Settings\[user]\Local Settings\Application Data\Microsoft\Team Foundation\3.0\Cache\VersionControl.config

I hope this helps.

If you liked this post, please be sure to subscribe to my RSS Feed.

A URL Friendly Guid, but Not Shorter…

17. August 2010 13:35 by Scott in   //  Tags:   //   Comments (0)

I have a website that gets thousands upon thousands of hits a day.  And I use guids to identifiy everything.  So I needed something to show Guids in the URLS.  The best thing I found at that moment was Mads Kristensen’s Shorter URL Friendly Guid

Mads basically converts the Guid to base 64.  For a small website of sorts, this isn’t a bad idea.  But overtime and larger websites there will be more and more Guids represented.  After coming up with several errors in my site, I decided to investigate.  When converting to Base64 with Guids, I started to notice some slight loss of the Guid.  When I say slight, I mean one in every 2000 users had shown errors.  To me this isn’t acceptable by any means.  One user can destroy an entire website by talking slander so I was in need of a fix. 

So I threw out Mads idea and went searching for something different.  Its not uncommon to still use Guids in URL’s.  With the Dashes and all.  Microsoft, Flickr, Yahoo, Google, and some various other third party websites still use them in their URLs.  But I didn’t want the dashes.  I wanted just the numbers and letters.  Dashes could some day cause a problem, but not just numbers and letters.  So I decided to get rid of the dashes.  So here is the final code to use Guids as Urls.

I have a Guid extension class in C#.  One method is as follows:

public static string RemoveDashes(this Guid guid)
{
 return guid.ToString().Replace("-","");
}

This method gets called when ever I convert a Guid to a URL.  Whats nice about this, is the way I convert the Guid back with dashes.  No real fiddling with strings.  All that needs to be done is this:

Guid guid = new Guid("c9a646d39c614cb7bfcdee2522c8f633");

And that automatically puts the dashes back into the system.

If you liked this post, please be sure to subscribe to my RSS Feed.

Binding LINQ to Silverlight Listview

13. August 2010 10:03 by Scott in   //  Tags:   //   Comments (0)

I hate having to look deep and hard and then when I don’t find anything on Google, I move into uncharted territory.  So here is some code on how to bind a Silverlight Listview with LINQ.

One point, I don’t care that much about making this that presentable, so here is what I wrote.  The LINQ could probably be built better, but if you know what I work or who I work for, you know that all I build is Demo Apps.  So this won’t be production, its just showing the fact that it can be done. This Demo shows Hurricanes in a Listview.  The list of hurricanes were pulled from the NOAA site.

A few things to point out:

  1. I pulled all the hurricanes from the DB and then started working on them.  So everything is already in cache.
  2. When doing Hierarchical data tempates, the ITEMSOURCE and ITEM templates are point to the the next lower level of the Template.  So if you look in the XAML, you will see the the item source and item templates point to the next layer down. I didn’t know this.

C# Service:

public class HurricaneServices : IHurricaneServices
    {
        public List<HurricanesClass> GetHurricanes()
        {
            var hurricanes = HurricanesClass.GetCachedHurricanes();

             return(from xx in hurricanes
                      group xx by xx.Hurricane_Name into gg
                      orderby gg.FirstOrDefault().DateTime_Reported descending
                      where gg.Key != null
                      select new HurricanesClass
                      {
                          Hurricane_Name = gg.Key.Replace(".mxd", ""),
                          Types = (from yy in hurricanes
                                   where yy.Hurricane_Name == gg.Key
                                   group yy by yy.Type into zz
                                   where zz.Key != null
                                   select new HurricanesClass
                                   {
                                       Type = zz.Key,
                                       Services = (from cc in hurricanes
                                                   where cc.Type == zz.Key
                                                   where cc.Hurricane_Name == gg.Key
                                                   orderby cc.DateTime_Reported descending
                                                   select new HurricanesClass
                                                   {
                                                       DateTime_Reported = cc.DateTime_Reported,
                                                       Webservice_Name = cc.Webservice_Name,
                                                       Webservice_URL = cc.Webservice_URL,
                                                   }).ToList()
                                   }).ToList()
                      }).ToList();
        }
    }

Here is the XAML it is binded to:

<Grid x:Name="LayoutRoot" Background="White">
        <Grid.Resources>
            <sdk:HierarchicalDataTemplate x:Key="HurricaneServices">
                <StackPanel MouseLeftButtonDown="StackPanel_MouseLeftButtonDown">
                    <TextBlock Text="{Binding Path=Webservice_Name}"></TextBlock>
                    <TextBlock Text="{Binding Path=DateTime_Reported}"></TextBlock>
                    <TextBlock x:Name="wsURL" Text="{Binding Path=Webservice_URL}"></TextBlock>
                </StackPanel>
            </sdk:HierarchicalDataTemplate>
            <sdk:HierarchicalDataTemplate x:Key="HurricaneTypes" ItemsSource="{Binding Path=Services}" ItemTemplate="{StaticResource HurricaneServices}">
                <StackPanel>
                    <TextBlock Text="{Binding Path=Type}"></TextBlock>
                </StackPanel>
            </sdk:HierarchicalDataTemplate>
            <sdk:HierarchicalDataTemplate x:Key="HurricaneNames" ItemsSource="{Binding Path=Types}" ItemTemplate="{StaticResource HurricaneTypes}">
                <StackPanel>
                    <TextBlock Text="{Binding Path=Hurricane_Name}"></TextBlock>
                </StackPanel>
            </sdk:HierarchicalDataTemplate>
        </Grid.Resources>
        <sdk:TreeView x:Name="mytree" ItemTemplate="{StaticResource HurricaneNames}" Grid.Row="0" Grid.Column="0" Height="300" Width="800" Background="Gray">
        </sdk:TreeView>
    </Grid>

And last but not least, the Binding Syntax.  The code behind of the XAML page.

     public HurricaneData()
        {
            InitializeComponent();
            HurricaneService.HurricaneServicesClient ws = new HurricaneService.HurricaneServicesClient();
            ws.GetHurricanesCompleted += new EventHandler<HurricaneService.GetHurricanesCompletedEventArgs>(webService_GetCustomersByLastNameCompleted);
            ws.GetHurricanesAsync();
                    }
        void webService_GetCustomersByLastNameCompleted(object sender, HurricaneService.GetHurricanesCompletedEventArgs e)
        {
            mytree.ItemsSource = e.Result;
        }
If you liked this post, please be sure to subscribe to my RSS Feed.

WCF Silverlight 4 Services error - The contract name could not be found in the list of contracts implemented by the service

9. August 2010 13:32 by Scott in   //  Tags:   //   Comments (0)

When developing WCF silverlight 4 services to contact data, I received the following error:

The contract name '’ could not be found in the list of contracts implemented by the service ‘’.

I wanted to just give a heads up to those wondering whats going on.  Make sure when you add the endpoint, your contract points to the Interface instead of just the service it self.  For example:

 <services>
      <service behaviorConfiguration="PortalSilverlight.Web.Services.ServicesBehavior" name="PortalSilverlight.Web.Services.Services">
        <endpoint address="http://localhost:3454/Services/Services.svc" binding="wsHttpBinding" contract="PortalSilverlight.Web.Services.IServices" />
      </service>
</services>

Notice in the contract attribute I am pointing towards the IService instead of just the Services.svc file.  Took me a couple of hours to figure this out.

If you liked this post, please be sure to subscribe to my RSS Feed.

Programmatically Open ShapeFiles with ArcObjects

6. August 2010 13:42 by Scott in   //  Tags:   //   Comments (61)

All,

Along with my last few posts, I received an Error when trying to open shapefiles with Arcobjects. Thought I would post the problem incase someone else ran into it.

Here is the code to open shapefiles with Arcobjects.

IWorkspaceFactory workspaceFactoryShape = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass(); //creates a shape factory to pull the shape and create the feature class.
IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactoryShape.OpenFromFile(System.IO.Path.GetDirectoryName(file), 0); //Opens the Shape file.
IFeatureLayer featureLayer = new FeatureLayerClass();
featureLayer.FeatureClass = featureWorkspace.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(file)); //opens the featurclass from the shapefile

 

Two things to point out.

  1. The openfromFile method will throw the error:  HRESULT: 0x80040258 if you don’t get the directory in which the shape files are located.  Its not looking for the actual .shp file.  Its looking for where the shape files reside. 
  2. The OpenFeatureclass method is where you give just the file name of the shape file.  Don’t include the .shp extenstion nor the file path.  Remember it already has the file path I stated in the first point.

Hope this helps someone out! I know I struggled with it for about 2 hours…

If you liked this post, please be sure to subscribe to my RSS Feed.

How to Download a File in C#

4. August 2010 13:32 by Scott in   //  Tags:   //   Comments (0)

The first example shows how to download a file synchronously and the second, asynchronously.  Just a quick post.  Thought it would help someone out that.

using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://yahoo.com/file.txt", @"c:\file.txt");

This one shows how to download a file in C# asynchronously.

private void btnDownload_Click(object sender, EventArgs e)
{
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
  webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), @"c:\myfile.txt");
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
  progressBar.Value = e.ProgressPercentage;
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
  MessageBox.Show("Download completed!");
}
If you liked this post, please be sure to subscribe to my RSS Feed.

How to publish a ArcMap to the ArcGIS Server…

4. August 2010 10:02 by Scott in   //  Tags:   //   Comments (46)

So after tons of searching and bothersome problems, It took a while to find code, but none could be found.  So I wanted to make sure the end example was easily findable on the internet next time.  Hope this saves some time of another programmer out there!

This code will publish an .MXD map to the ArcGIS server.  And turn it on to be used right away.

 //The following C# code shows how to connect to the ArcGIS Server called "     ",
        //and use the IServerObjectConfiguration interface to set the properties of
        //a new server object configuration. The new configuration is created and
        // added to the server with the 
        //CreateConfiguration and AddConfiguration methods on IServerObjectAdmin.
        /// <summary>
        /// This publishes a Map to the ArcGIS Server
        /// </summary>
        /// <param name="serverMachineName">Servername</param>
        /// <param name="serviceName">Service name in which you want to call it</param>
        /// <param name="pathToMap">File Path to the .mxd map.</param>
        /// <param name="format">Which format you would like.  Look in code.</param>
        public static void AddMapService(string serverMachineName, string serviceName, string pathToMap, int format)
        {
            // Initialize ESRI licenses
            IAoInitialize aoInit = new AoInitializeClass();
            aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcServer);

            //define paths for the onlineresource property in the extension properties
            string resource = "http://" + serverMachineName + "/ArcGIS/services/" + serviceName + "/MapServer/WMSServer";
            string resourceKML = "http://" + serverMachineName + "/ArcGIS/services/" + serviceName + "/MapServer/KMLServer";
            string resourceWCS = "http://" + serverMachineName + "/ArcGIS/services/" + serviceName + "/MapServer/WCSServer";
            string resourceWFS = "http://" + serverMachineName + "/ArcGIS/services/" + serviceName + "/MapServer/WFSServer";

            //  Connect to the ArcGIS server called  serverMachineName (string) .   
            IGISServerConnection pGISServerConnection = new GISServerConnectionClass();
            // example :  pGISServerConnection.Connect("llv38-tasc65688");   
            pGISServerConnection.Connect(serverMachineName);

            // create the new configuration
            IServerObjectAdmin pServerObjectAdmin = pGISServerConnection.ServerObjectAdmin;
            IServerObjectConfiguration pConfiguration = pServerObjectAdmin.CreateConfiguration();
            IServerObjectConfiguration2 pConfiguration2 = (IServerObjectConfiguration2)pConfiguration;
            IServerObjectConfiguration3 pConfiguration3 = (IServerObjectConfiguration3)pConfiguration;

            // set the   General Configuration Settings
            pConfiguration.Name = serviceName;           //  the name of this configuration
            pConfiguration.TypeName = "MapServer";   // the type of server object to be created
            pConfiguration.IsPooled = true;
            pConfiguration.MinInstances = 1;
            pConfiguration.MaxInstances = 2;
            pConfiguration.WaitTimeout = 60;
            pConfiguration.UsageTimeout = 600;
            pConfiguration.StartupType = esriStartupType.esriSTAutomatic;
            pConfiguration.IsolationLevel = esriServerIsolationLevel.esriServerIsolationHigh;

            //  Set the configuration Properties of the MapServer Object
            IPropertySet pProps = pConfiguration.Properties;
            pProps.SetProperty("FilePath", pathToMap);    // required property
            pProps.SetProperty("OutputDir", "c:\\arcgisserver\\arcgisoutput");
            string virtualOutDir = " http://" + serverMachineName + "/arcgisoutput";
            pProps.SetProperty("VirtualOutputDir", virtualOutDir);
            pProps.SetProperty("MaxImageHeight", "2048");
            pProps.SetProperty("MaxRecordCount", "500");
            pProps.SetProperty("MaxBufferCount", "100");
            pProps.SetProperty("MaxImageWidth", "2048");
            pConfiguration.Properties = pProps;

            //  Set the info segment of the MapServer Object  properties
            IPropertySet info = pConfiguration2.Info;
            info.SetProperty("WebEnabled", "true");
            info.SetProperty("WebCapabilities", "Map,Query,Data");
            pConfiguration2.Info = info;

            //  Set the recycle properties of the MapSrver object
            IPropertySet pProp = pConfiguration.RecycleProperties;
            pProp.SetProperty("StartTime", "1:00 AM");    //   start recycling at midnight
            pProp.SetProperty("Interval", "86400");      //  every 24 hours
            pConfiguration.RecycleProperties = pProp;

            bool enabled;
            if (format == 1 || format == 15)
            {   //Set WMS extension Properties
                pConfiguration2.set_ExtensionEnabled("WmsServer", true);

                IPropertySet pExtensionProps = pConfiguration2.get_ExtensionProperties("WmsServer");
                pExtensionProps.SetProperty("OnlineResource", resource);
                pExtensionProps.SetProperty("Name", "WMS");
                pExtensionProps.SetProperty("Title", serviceName);
                // pConfiguration2.set_ExtensionProperties("WmsServer", pExtensionProps);

                IPropertySet pProp2 = pConfiguration2.get_ExtensionInfo("WmsServer");
                pProp2.SetProperty("WebEnabled", "true");
                pProp2.SetProperty("WebCapabilities", "Map,Query,Data");
                pConfiguration2.set_ExtensionInfo("WmsServer", pProp2);
            }

            if (format == 2 || format == 15)
            {    //  Set KML extension properties
                pConfiguration2.set_ExtensionEnabled("KMLServer", true);

                IPropertySet pPropKML = pConfiguration2.get_ExtensionInfo("KMLServer");
                pPropKML.SetProperty("WebEnabled", "true");
                pPropKML.SetProperty("WebCapabilities", "SingleImage,SeparateImages,Vectors");
                pConfiguration2.set_ExtensionInfo("KMLServer", pPropKML);

                IPropertySet pExtensionPropKML = pConfiguration2.get_ExtensionProperties("KMLServer");
                pExtensionPropKML.SetProperty("ImageSize", "1024");
                pExtensionPropKML.SetProperty("FeatureLimit", "1000000");
                pExtensionPropKML.SetProperty("Dpi", "96");

                pExtensionPropKML.SetProperty("MinRefreshPeriod", "30");
                pExtensionPropKML.SetProperty("UseDefaultSnippets", "false");
                //       pConfiguration2.set_ExtensionProperties("KMLServer", pExtensionPropKML);
            }

            if (format == 4 || format == 15)
            {   //Set WCS extension Properties
                pConfiguration2.set_ExtensionEnabled("WcsServer", true);

                IPropertySet pExtensionPropsWCS = pConfiguration2.get_ExtensionProperties("WcsServer");
                pExtensionPropsWCS.SetProperty("OnlineResource", resourceWCS);
                pExtensionPropsWCS.SetProperty("Name", "WCS");
                pExtensionPropsWCS.SetProperty("Title", serviceName);
                // pConfiguration2.set_ExtensionProperties("WcsServer", pExtensionPropsWCS);

                IPropertySet pPropWCS = pConfiguration2.get_ExtensionInfo("WcsServer");
                pPropWCS.SetProperty("WebEnabled", "true");
                pConfiguration2.set_ExtensionInfo("WcsServer", pPropWCS);
            }


            if (format == 8 || format == 15)
            {   //Set WFS Extension Properties
                pConfiguration2.set_ExtensionEnabled("WfsServer", true);

                IPropertySet pExtensionPropsWFS = pConfiguration2.get_ExtensionProperties("WfsServer");
                pExtensionPropsWFS.SetProperty("OnlineResource", resourceWFS);
                pExtensionPropsWFS.SetProperty("Name", "WFS");
                pExtensionPropsWFS.SetProperty("Title", serviceName);
                pExtensionPropsWFS.SetProperty("AppSchemaURI", resourceWFS);
                pExtensionPropsWFS.SetProperty("AppSchemaPrefix", serviceName);
                //     pConfiguration2.set_ExtensionProperties("WfsServer", pExtensionPropsWFS);

                IPropertySet pPropWFS = pConfiguration2.get_ExtensionInfo("WfsServer");
                pPropWFS.SetProperty("WebEnabled", "true");
                pConfiguration2.set_ExtensionInfo("WfsServer", pPropWFS);
            }

            //' add the configuration to  the server
            pServerObjectAdmin.AddConfiguration(pConfiguration2);
            pServerObjectAdmin.StartConfiguration(serviceName, "MapServer");
        }  //  end method
If you liked this post, please be sure to subscribe to my RSS Feed.