Sunday, October 16, 2011

ASP.NET Master Page and Other Pages allignment Issues

I was creating a website with ASP.NET master page and other content pages.

For some reason when I was navigating from one page to another there was a shift in the footer. I had a horizontal line above the footer and this was jumping few pixels up and down when navigating through the pages.

After some research, I found out that this was happening because some of the pages had the paragraph (<p> </p>) tags and this was pushing the content a little bit.

I resolved this by adding a proper margin and padding to the div body in the master page itself.

Hope this tip can help you !

Sunday, September 25, 2011

Class Deserializing issue with a class containing ArrayList as member variable


In one of my program, I had a class declared with a Member Variable whose datatype is ArrayList.

I serialized and saved the class contents in the text file.

When I tried to deserialize, I got back only the first value in the ArrayList, not all the values. Even though the file had more than 1 value, always I was getting back only one value into my class member variable.

After several debugging I thought of adding a constructor to the class and also inside that class constructor I initialized the ArrayList member variable to new ArrayList. After doing this then the deserialization happened properly. Then I got all my values back into my ArrayList member variable.

Whenever deserialization occurs the class constructor is called and proper initialization happens and then the ArrayList is being filled.

Hope this tip saves time for someone !


Wednesday, August 24, 2011

Creating hotspots on image

Team,

I was asked to create a simple web page with a static image and hotspots (hyperlinks which will navigate to other pages) on some of the image features.

Did some digging work and was able to write this code.

Here is the working link.

The link above contains two visible hotspots and one invisible hotspot.

Key points are :

1. The main DIV tag must contain the background image with style position relative.

2. The inner hyperlinks must contain style position absolute and you can place those hyperlinks wherever you want on the image.

I have added the source code below.

Happy coding !

Cheers
Anand

================

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
    <title>Hotspot on Image</title>
</head>
<body style="text-align: center;">
    <div id="divMain" style="background-image: url('sampleImage.png'); width: 528px;
        height: 396px; position: relative;">
        <a id="birdyahoo" href="
http://www.yahoo.com" target="_blank" style="border: medium solid Red;
            width: 46px; height: 75px; position: absolute; left: 186px; top: 81px;" title="Click here to visit Yahoo Website">
        </a><a id="birdGoogle" href="
http://www.google.com" target="_blank" style="border: medium solid Red;
            width: 92px; height: 64px; position: absolute; left: 184px; top: 255px;" title="Click here to visit Google Website">
        </a><a id="birdMicrosoft" href="
http://www.microsoft.com" target="_blank" style="width: 69px; height: 38px; position: absolute; left: 347px; top: 162px;" title="Click here to visit Microsoft Website">
        </a>
    </div>
</body>
</html>


================

Sunday, July 24, 2011

Send E-Mail using ASP.NET

Team, I got involved in a project where we need to send e-mail from ASP.NET web application.

Tried many techniques and got all these errors .


"Mailbox unavailable. The server response was: DY-001 (SNT0-MC4-F22) Unfortunately, messages from 76.175.219.250 weren't sent. Please contact your Internet service provider. You can tell them that Hotmail does not relay dynamically-assigned IP ranges. You can also refer your provider to http://mail.live.com/mail/troubleshooting.aspx#errors."
 "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first"

"Mailbox unavailable. The server response was: 5.7.3 Requested action aborted; user not authenticated"
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

After few research here is the final working code.

public static bool SendMessage()
{
            bool togoValue = false;
            try
            {
                MailMessage mm = new MailMessage();
                mm.Sender = new MailAddress("fromEmailID@hotmail.com");
                mm.From = new MailAddress("fromEmailID@hotmail.com ");
                mm.To.Add(new MailAddress( "toEmailID@hotmail.com "));
                mm.Subject = "This is test Subject";
                mm.Body = "This is test Body";
                SmtpClient client = new SmtpClient("smtp.live.com");
                client.Credentials = new NetworkCredential("fromEmailID@hotmail.com", "password");
                client.Port = 25;
                client.EnableSsl = true;
                client.Send(mm);
                togoValue = true;
            }
            catch (Exception ex)
            {
                throw new Exception("Error when sending mail." + ex.ToString());
            }
            return togoValue;
 }

Replace your values in the right location and give it a try.

I tried both GMail server (smtp.gmail.com) and Hotmail Server (smtp.live.com) and both are working fine.

Have fun coding !

Tuesday, June 7, 2011

ListBox Control DisplayMember Property Issue

My goal was to add a ListBox Control and add Class Objects Items to it. The Display Values should be one of the class member variables.

I have declared a string variable  (m_Name) which is public (It's basically a "Field" of the class) and then I also assigned the ListBoxControl.DisplayMember = "m_Name" ;

This was not working and the ListBox Control was always showing the Class.ToString() value and not my expected class member value.

After few Googling,  I found out that it should be a "Property" of the class not the "Field".

Once I created a "Property" and assigned it to the ListBoxControl.DisplayMember then it started to display the correct value.

Hope this saves some time.

Happy Coding !

Monday, May 23, 2011

Wrap Text in Silverlight Datagrid Columns

The old code shows how the text column was bound to a Key-Value pair. But the problem was if the value is larger, then it will exceed the 190 pixels width.

To resolve the problem, I have to use a "CellTemplate" and "DataTemplate" as shown in the new code. The "TextWrapping" element is the key.

Happy Coding.



OLD CODE:
<data:DataGrid.Columns>
<data:DataGridTextColumn Binding="{Binding Path=Key}" FontWeight="Bold" Width="120" />
<data:DataGridTextColumn Binding="{Binding Path=Value}" Width="190" />
</data:DataGrid.Columns>

NEW CODE:
<data:DataGrid.Columns>
<data:DataGridTemplateColumn>
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Key}" FontWeight="Bold" Width="118" TextWrapping="Wrap" Margin="2,2,2,2" ></TextBlock>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
<data:DataGridTemplateColumn>
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Value}" FontWeight="Normal" Width="188" TextWrapping="Wrap" Margin="2,2,2,2" ></TextBlock>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
</data:DataGrid.Columns>

Friday, April 22, 2011

Passing SQL String as Query String in Web Applications

I was working on a web page where I had to pass a SQL Query string to another page as query parameter.

When I finished the coding and tested, it was working for some queries and failing for certain. After a close examination I found out it was failing for "LIKE" queries. The query had characters like '%'

For example if the query is like "SELECT FNAME LIKE '%ANA%'" then this will fail. Because the receiving page was unable to pass the query string properly.

After some research I found out there is a javascript function encodeURI() which will encode the query string.

There is also another function decodeURI() which does opposite of encodeURI().

By using these functions I was able to complete the coding.



Visual Studio 2010 Compilation Error

While working with Visual Studio 2010 in Silverlight coding I got this error message.

"Unable to attach to application. The version of clr.dll in the target does not match the one mscordacwks.dll was built for.Do you want to continue anyway ?"

I tried cleaning up the solution and rebuilding still did not fix anything.

Finally after some research I found out that this error happens when the Windows Updates is on progress.

I waited till Windows updates are complete and then restarted the laptop.

Then recompiled and it worked.

Hope this helps.

Here is the snapshot of the error image.

Monday, March 21, 2011

Embed Video in Silverlight

Friends,
Here is the code snippet to embed a Video File in Silverlight.

I tried it with .wmv file and it worked fine.

Hope it helps someone !

Cheers
Anand


XAML File Content

        <Border x:Name="BorderVideo" BorderThickness="5" BorderBrush="Blue"  CornerRadius="25" Canvas.ZIndex="1" Width="670" Height="550"  >
            <StackPanel Orientation="Vertical">
                <MediaElement x:Name="ChurchSong"
                      Width="640"
                      Height="480"
                      AutoPlay="False"
                      Source="MVI_0957_WMV V9.wmv" Canvas.ZIndex="0" >
                </MediaElement>
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
                    <Button x:Name="buttonStopandRewind" Content="Stop and Rewind" Width="100" Margin="10,10,10,10" Click="buttonStopandRewind_Click" />
                    <Button x:Name="buttonPause" Content="Pause" Width="100" Margin="10,10,10,10" Click="buttonPause_Click" />
                    <Button x:Name="buttonPlay" Content="Play" Width="100" Margin="10,10,10,10" Click="buttonPlay_Click" />
                    <Button x:Name="buttonSkip" Content="Skip 5 Secs" Width="100" Margin="10,10,10,10" Click="buttonSkip_Click" />
                </StackPanel>
            </StackPanel>
        </Border>

.cs File Content
      private void buttonStopandRewind_Click(object sender, RoutedEventArgs e)
        {
            this.ChurchSong.Stop();
        }

        private void buttonPause_Click(object sender, RoutedEventArgs e)
        {
            this.ChurchSong.Pause();
        }

        private void buttonPlay_Click(object sender, RoutedEventArgs e)
        {
            this.ChurchSong.Play();
        }

        private void buttonSkip_Click(object sender, RoutedEventArgs e)
        {
            this.ChurchSong.Position = this.ChurchSong.Position.Add(new TimeSpan(0, 0, 5));
        }

Thursday, February 24, 2011

ArcIMS, Tomcat and IReport Issues

Team,
I got a task to create some new IReport Templates. IReports will compile the report template into .jasper files which can be called from a .jsp application. It’s all Java and open source.
 This IReport application was installed on a Windows 2003 Server running ArcIMS 9.2 Build 514.2165, Apache Tomcat 5.5 and JDK 1.5.0_15.  
The first problem I faced was, the reports were blank. In the preview it will work fine. But when the .jsp file calls the .jasper file, only the Header and Footer will show-up but not the detailed data section of the report. I posted the problem in this link.
After researching many links I copied few selected .jar files of the IReport\modules\ext folder to the Tomcat\lib folder then I got this error.
================================================================
ERROR: failed to generate report...
...Error: java.lang.ClassCastException: cannot assign instance of net.sf.jasperreports.engine.base.JRBaseRectangle to field net.sf.jasperreports.engine.base.JRBasePen.penContainer of type net.sf.jasperreports.engine.JRPenContainer in instance of net.sf.jasperreports.engine.base.JRBasePen
================================================================
Again did some more research and I found copying .jar files in the %JAVA_HOME%\jre\lib\ext folder might help? But it didn’t.
The biggest problem was to find the exact .jar files which is required by the IReport latest version 4.0. Whenever I copied the new version .jar files either ArcIMS will break or IReports will not work. IReports latest version 4.0 never worked for me.
Then finally I decided to rollback with an advice of a friend. There was an IReport 1.3.3 version installed on the same server. Once I rolled back to this old version then everything started to work fine.
In conclusion with the existing ArcIMS/Java and Tomcat combination IReport latest version 4.0 will not work.
If I find a workaround I will post back again.

Tuesday, February 8, 2011

Could not load type Pagebase


This error showed up when I uploaded my ASP.NET AJAX enabled website to my IIS Webhosting service provider. I was breaking my head and thinking what went wrong.

I published my application in a sub-folder inside the main root folder.
The new application I was trying to publish was inside a subfolder like www.advancedtechnologyworks.com\PrayerHelp\
I was checking the Web.Config file inside the sub-folder “PrayerHelp” and all was fine.
Then finally I discovered there was another “Web.Config” on the main domain which was causing this issue.
The Web.Config file was like this
<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
       <appSettings/>
       <connectionStrings>
       </connectionStrings>
       <system.web>
              <compilation debug="true" targetFramework="4.0">
              </compilation>
              <authentication mode="Windows"/>
              <pages pageBaseType="PageBase" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
              </pages>
              <anonymousIdentification enabled="true"/>
              <customErrors mode="Off"/>
              <profile enabled="false">
                     <properties>
                           <!-- Available values for the StyleSheetTheme attribute: "Green", "Brown", "Red".-->
                           <add name="StylesheetTheme" defaultValue="Red" allowAnonymous="true"/>
                     </properties>
              </profile>
       </system.web>
</configuration>

I also identified this “PageBase.cs” file was inside the “App_Code” folder in the main domain folder.
I created the same “App_Code” folder inside the sub-folder “PrayerHelp” and copied this “PageBase.cs” file.  Eureka!  Everything started to work.
So when this error shows up, examine all the Web.Config files and see whether there is a reference to a new class file and make sure that class file is placed inside the App_Code folder.
Hope this tip helps someone.


Wednesday, January 19, 2011

ArcGIS Silverlight API Printing with Map to Scale

Printing in ArcGIS Silverlight API needs some special coding. To print Map to scale, I have introduced a duplicate Map Control and copying the layers to this control during Print operation.
Here is the working XAML code and the C Sharp code.


XAML code

<UserControl xmlns:esriToolkitPrimitives="clr-namespace:ESRI.ArcGIS.Client.Toolkit.Primitives;assembly=ESRI.ArcGIS.Client.Toolkit"  xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="SL4Print.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="500" d:DesignWidth="800" xmlns:esri="http://schemas.esri.com/arcgis/client/2009">

    <Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="60"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>

       <esri:Map Background="White" Name="mapControl" Grid.Row="0" Grid.Column="0" ExtentChanged="mapControl_ExtentChanged" Progress="mapControl_Progress" >
            <esri:ArcGISDynamicMapServiceLayer ID="United States" Url="http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer" >
            </esri:ArcGISDynamicMapServiceLayer>
  
           
        </esri:Map>
 
        <Button x:Name="InvokePrint" Grid.Row="1" Grid.Column="0" Content="Click Button to Print" Width="200" Height="50"  Click="InvokePrint_Click" />

        <Border x:Name="borderprintMap" BorderThickness="0" BorderBrush="Blue" Width="1056" Height="816" Canvas.ZIndex="-5" Grid.Row="0" >
            <Canvas x:Name="canvasPrint">

                <Border x:Name="borderHeader" Background="SkyBlue">
                    <TextBlock x:Name="headerText" Text="{Binding ElementName=textboxHeader, Path=Text }" TextAlignment="Center" >
                    </TextBlock>
                </Border>
               
                <Canvas>
                   
                    <esri:Map Background="White" Name="mapPrint"   IsLogoVisible="False"  HorizontalAlignment="Center" VerticalAlignment="Center">
                    </esri:Map>
                    <Border x:Name="bordermapPrintScalebar">
                        <esri:ScaleBar Map="{Binding ElementName=mapPrint }"  DisplayUnit="Miles" HorizontalAlignment="Center"  VerticalAlignment="Center"/>
                    </Border>
                </Canvas>
                <Border x:Name="borderFooter" Background="SkyBlue" >
                    <TextBlock x:Name="footerText" Text="{Binding ElementName=textboxFooter, Path=Text}" TextAlignment="Center" HorizontalAlignment="Left">
                    </TextBlock>
                </Border>
           
            </Canvas>
        </Border>
       
        <Border x:Name="borderprintSetup" Width="350" Height="150" Background="LightGray" CornerRadius="20" BorderThickness="2" BorderBrush="Black" Visibility="Collapsed">
            <StackPanel>
            <Grid ShowGridLines="False">
                <Grid.RowDefinitions>
                    <RowDefinition Height="50"></RowDefinition>
                    <RowDefinition Height="50"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100"></ColumnDefinition>
                    <ColumnDefinition Width="250"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <sdk:Label Grid.Row="0" Grid.Column="0" Content="Header Text : " VerticalAlignment="Center" HorizontalAlignment="Right" ></sdk:Label>
                <sdk:Label Grid.Row="1" Grid.Column="0" Content="Footer Text : " VerticalAlignment="Center" HorizontalAlignment="Right" ></sdk:Label>
                    <TextBox x:Name="textboxHeader" Grid.Row="0" Grid.Column="1" Width="200" VerticalAlignment="Center" HorizontalAlignment="Center" Text="Header"/>
                    <TextBox x:Name="textboxFooter" Grid.Row="1" Grid.Column="1" Width="200" VerticalAlignment="Center" HorizontalAlignment="Center" Text="Footer"/>
            </Grid>
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" >
                    <Button x:Name="Print" Content="Print"  Width="50" VerticalAlignment="Bottom"  HorizontalAlignment="Left" Margin="10,10,10,10" Click="Print_Click" />
                    <Button x:Name="Cancel" Content="Cancel" Width="50" VerticalAlignment="Bottom"  HorizontalAlignment="Right" Margin="10,10,10,10" Click="Cancel_Click" />
                </StackPanel>
            </StackPanel>
        </Border>
    </Grid>
</UserControl>


C Sharp Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Printing;
using ESRI.ArcGIS.Client;
using System.Windows.Media.Imaging;

namespace SL4Print
{
    public partial class MainPage : UserControl
    {
        bool performPrintSetup = true;

        public MainPage()
        {
            InitializeComponent();
        }

        private void createPrintMapControl()
        {
            mapPrint.Layers.Clear();
            mapPrint.Extent = mapControl.Extent;
            foreach (Layer eachLayer in mapControl.Layers)
            {
                try
                {
                    ArcGISDynamicMapServiceLayer dynamicLayer = eachLayer as ArcGISDynamicMapServiceLayer;
                    if (dynamicLayer != null)
                    {
                        ArcGISDynamicMapServiceLayer newDynamicLayer = new ArcGISDynamicMapServiceLayer();
                        newDynamicLayer.Url = dynamicLayer.Url;
                        newDynamicLayer.Opacity = dynamicLayer.Opacity;
                        dynamicLayer.VisibleLayers = dynamicLayer.VisibleLayers;
                        mapPrint.Layers.Add(newDynamicLayer);
                    }
                    ArcGISTiledMapServiceLayer tiledLayer = eachLayer as ArcGISTiledMapServiceLayer;
                    if (tiledLayer != null)
                    {
                        ArcGISTiledMapServiceLayer newTiledLayer = new ArcGISTiledMapServiceLayer();
                        newTiledLayer.Url = tiledLayer.Url;
                        newTiledLayer.Opacity = tiledLayer.Opacity;
                        mapPrint.Layers.Add(newTiledLayer);
                    }
                    GraphicsLayer graphicsLayer = eachLayer as GraphicsLayer;
                    if (graphicsLayer != null)
                    {
                        GraphicsLayer newGraphicsLayer = new GraphicsLayer();
                        newGraphicsLayer = graphicsLayer;
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show("Error when setting up Print Template : " + ex.Message);
                }
            }
        }

        void thePrintDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            // Header Control
            //borderHeader.Background = new SolidColorBrush(Colors.White);
            borderHeader.BorderThickness = new Thickness(2.0);
            borderHeader.BorderBrush = new SolidColorBrush(Colors.Black);
            borderHeader.SetValue(Canvas.ZIndexProperty, 1);
            borderHeader.SetValue(Canvas.TopProperty, 0.0);
            borderHeader.Width = e.PrintableArea.Width;
            //Map Control
            mapPrint.Width = e.PrintableArea.Width;
            mapPrint.Height = e.PrintableArea.Height;
            // Scalebar Control
            bordermapPrintScalebar.Width = e.PrintableArea.Width;
            bordermapPrintScalebar.SetValue(Canvas.TopProperty, (e.PrintableArea.Height - 35));
            bordermapPrintScalebar.SetValue(Canvas.LeftProperty, 0.0);
            bordermapPrintScalebar.SetValue(Canvas.ZIndexProperty, 1);
            bordermapPrintScalebar.Background = new SolidColorBrush(Colors.Gray);
            // Scale and Footer Control
            //borderFooter.Background = new SolidColorBrush(Colors.White);
            borderFooter.BorderThickness = new Thickness(2.0);
            borderFooter.BorderBrush = new SolidColorBrush(Colors.Black);
            borderFooter.SetValue(Canvas.ZIndexProperty, 1);
            borderFooter.SetValue(Canvas.TopProperty, (e.PrintableArea.Height - 20));
            borderFooter.Width = e.PrintableArea.Width;

            e.PageVisual = canvasPrint;
            e.HasMorePages = false;

        }

        private void mapControl_ExtentChanged(object sender, ExtentEventArgs e)
        {
            mapPrint.Extent = mapControl.Extent;
        }

        private void mapControl_Progress(object sender, ProgressEventArgs e)
        {
            if (e.Progress == 100)
            {
                if (performPrintSetup == true)
                {
                    createPrintMapControl();
                    performPrintSetup = false;
                }
            }
        }

     
        void thePrintDoc_EndPrint(object sender, EndPrintEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
            MessageBox.Show("Printing Completed !");
        }

        void thePrintDoc_BeginPrint(object sender, BeginPrintEventArgs e)
        {
            this.Cursor = Cursors.Wait;
        }

        private void InvokePrint_Click(object sender, RoutedEventArgs e)
        {
            borderprintSetup.Visibility = System.Windows.Visibility.Visible;
        }

        private void Print_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                PrintDocument thePrintDoc = new PrintDocument();
                thePrintDoc.BeginPrint += new EventHandler<BeginPrintEventArgs>(thePrintDoc_BeginPrint);
                thePrintDoc.EndPrint += new EventHandler<EndPrintEventArgs>(thePrintDoc_EndPrint);
                thePrintDoc.PrintPage += new EventHandler<PrintPageEventArgs>(thePrintDoc_PrintPage);
                thePrintDoc.Print("Silverlight 4 Sample Print");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            borderprintSetup.Visibility = System.Windows.Visibility.Collapsed;
        }


        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            borderprintSetup.Visibility = System.Windows.Visibility.Collapsed;
        }


        
    }
}


All Blogs so far ...