Sunday, March 23, 2014

Using Events and Delegates in Visual C#.NET


Here are the steps to create events and delegates in .NET.
 
STEP 1:

In the Child Control which raises the event, you should have the following:

public delegate void ZoomtoMapEventHandler(object sender, ClassQueryResultsSet CQRe);

public event ZoomtoMapEventHandler ZoomtoMapEvent;

where the ClassQueryResultsSet is as follows :

public class ClassQueryResultsSet : EventArgs
                {
                                public DataSet QueryResultsDataSet ;
                                public string QueryResultsTableName ;
                                public string KeyFieldName ;
                                public ClassQueryResultsSet()
                                {
                                                //
                                                // TODO: Add constructor logic here
                                                //
                                                QueryResultsDataSet = null ;
                                                QueryResultsTableName = null ;
                                                KeyFieldName = "" ;
                                }
                }

Also when invoking the event check for null and do it as shown below:

                                                                if (ZoomtoMapEvent != null)
                                                                {
                                                                                ZoomtoMapEvent(this, Res) ;
                                                                }
                                                                else
                                                                {
                                                                                MessageBox.Show("ZoomtoMapEvent is Null !") ;
                                                                }

STEP 2

In the MAIN PARENT Program, the event is declared like below

x.userControlQuerySingleTable1.ZoomtoMapEvent += new WindowsControlLibrarySingleTable.UserControlQuerySingleTable.ZoomtoMapEventHandler(x.ShowMaptoUser)  ;

 
Also the function into which the control should come in should have the same signature as shown below:

public void ShowMaptoUser(object o, ClassQueryResultsSet e)
{
                MessageBox.Show("Calling ok" + e.QueryResultsTableName) ;
}

Using this events and delegates will come in handy when passing information from one class to another.

Happy coding.

Cheers
Adam

Monday, February 24, 2014

Simple Slideshow using timer, javascript and JQuery


Here is the code to create a simple slideshow using timer, JavaScript and JQuery.

The html file contents should be like this which has all the images to show up.

<div class="galleryImages">
<img src='Images/Slides/0.png' alt="" />
<img src='Images/Slides/1.png' alt="" />
<img src='Images/Slides/2.png' alt="" />
<img src='Images/Slides/3.png' alt="" />
</div>
 
The 'galleryImages' class is defined like this.

.galleryImages {
position: relative;
height: 350px;
width:700px;
overflow: hidden;
border:solid;
border-color:black;
border-width:thin;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
-khtml-border-radius: 15px;
border-radius: 15px;
margin:10px;
}
 
.galleryImages img {
position: absolute;
top: 0;
left: 0;
}


The JavaScript code should be like this.

var slideShowTimer;
var imageId = 0;
var galleryImages;
var transitionSpeed = 500;

function PerformInitialization() {
SetupTimer();galleryImages = $('.galleryImages img');
}
 
function SetupTimer() {
slideShowTimer = setInterval(ChangePhoto, 3000);
}
 
function ChangePhoto() {
galleryImages.eq(imageId).stop(true, true).animate({ opacity: 0 }, transitionSpeed);
imageId++;if (imageId >= galleryImages.length) {
imageId = 0;
}
galleryImages.eq(imageId).stop(true, false).animate({ opacity: 1 }, transitionSpeed);
}

Make sure to call PerformInitialization() function during "onload" of the body of the html file.

Also make sure to add these "JQuery" references.

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script>

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"></script>
   
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/flick/jquery-ui.css" rel="stylesheet" type="text/css" />

Have fun. Happy coding.

Cheers
Adam

Friday, January 24, 2014

Attaching to an Event Trigger in Silverlight

There was a case in one of my projects to get notified whenever a Side Panel Visibility is changed.

For example, when a Panel Visibility state changes from "Collapsed" to "Visible" or from "Visible" to "Collapsed" we wanted a function to be called.

Here is the code to achieve this.

This line tells how to register it.

RegisterForNotification("Visibility", SidePanel, SidePanelVisibilityChanged);

Here is the function "RegisterForNotification".

public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
{//Bind to a depedency property
Binding b = new Binding(propertyName) { Source = element };

var prop = System.Windows.DependencyProperty.RegisterAttached( "ListenAttached"+propertyName, typeof(object), typeof(UserControl), new System.Windows.PropertyMetadata(callback));
 
element.SetBinding(prop, b);
}

This is the callback function which will be called whenever the visibility state changes.

private void SidePanelVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{  if (e.NewValue != null)
  {   if (e.NewValue.ToString() == "Collapsed")
   {     // Do something for collapsed... 
    }
  }
}

Hope this helps you.

Enjoy coding !

Cheers
Adam 
 
 

Tuesday, December 24, 2013

Using HTTP Modules


HTTP Modules are assemblies which can be called during every http request.

This comes in very handy when there is a need to intercept every request that comes into the Web application.

This is basically a simple class that is derived from IHttpModule interface.

Here is the sample code. This will be compiled to a DLL file.


public class MyClass : IHttpModule
{
        /// <summary>
        /// This is the disposing function.
        /// </summary>
        void IHttpModule.Dispose()
        {

        }

        /// <summary>
        /// This is the initialization function.
        /// </summary>
        /// <param name="context">This is the httpApplication context.</param>
        void IHttpModule.Init(HttpApplication httpApp)
        {
            httpApp.BeginRequest += new EventHandler(context_BeginRequest);
        }

        /// <summary>
        /// This is where the Begin Request Action is taking place.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication httpApp = (HttpApplication)sender;
            RequestManipulation(httpApp);
        }

        /// <summary>
        /// This is the core function which tries to alter the request.
        /// </summary>
        private void RequestManipulation(HttpApplication httpApp)
        {
                    AlterNameValueCollection(httpApp);
        }

       /// <summary>
        /// Writes details of the Form NameValueCollection in the REQUEST object.
        /// </summary>
        /// <param name="httpApp">This is the input HttpApplication context from which the request header details will be written out.</param>
        private void AlterNameValueCollection(HttpApplication httpApp)
        {
            NameValueCollection postInfo = httpApp.Request.Form;
            System.Reflection.PropertyInfo prop = httpApp.Request.Form.GetType().GetProperty("IsReadOnly", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            // Set the property false (writable)
            prop.SetValue(httpApp.Request.Form, false, null);
            foreach (String eachKey in postInfo.AllKeys)
            {
                string towrite = string.Format("Key : {0} - Value : {1}", eachKey, httpApp.Request.Form[eachKey]);
                Helper.WriteinFile(towrite);
                if (eachKey == "AuthorName")
                {
                    Helper.WriteinFile("Before Changing AuthorName value....");
                    string oldValue = httpApp.Request.Form[eachKey].ToString();
                    httpApp.Request.Form[eachKey] = "MyClass Success. The old value '" + oldValue + "' was modified by the MyClass dll." ;
                    Helper.WriteinFile("Just now changed the AuthorName value.");
                }
            }
        }
}

After this code is compiled, copy the DLL file to the "bin" folder of the ASP.NET application on which the requests should be intercepted.

This DLL will be loaded into memory by using the following entries in the "Web.Config" file.

  <system.webServer>
    <modules>
      <add name="MyClass" type="MyNamespace.MyClass, MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=77ced88f9fdf21cb" preCondition="managedHandler,runtimeVersionv4.0" />
    </modules>
  </system.webServer>
 
This DLL can also be installed in the "Global Assembly Cache" and the above entries should load it automatically.

Hope this blog helps.

Happy coding !

Cheers
Adam
 
 




 
 

Friday, November 29, 2013

Getting ASP.NET page values from Silverlight


There was a need to obtain values from the ASP.NET page to Silverlight application.

This is the function that can get the value.

private string GetHtmlElementValue(string htmlElementId)
{
   string togoElementValue = "";
   HtmlDocument doc = HtmlPage.Document;
   if (doc == null)
   {
     MessageBox.Show("Html Document is null.","Error", MessageBoxButton.OK);
      return togoElementValue;
   }
   HtmlElement elm = doc.GetElementById(htmlElementId);
   if (elm == null)
   {
     MessageBox.Show("Html Element " + htmlElementId + " is null.", "Error", MessageBoxButton.OK);
     return togoElementValue;
   }
     togoElementValue = elm.GetAttribute("value");
     return togoElementValue;
}

This is how the function should be called.

GetHtmlElementValue("AuthenticationTypeField");

This will come in handy when we need to pass the information from ASP.NET page to Silverlight Application.

Hope this helps.

Cheers
Adam



 
 
 

All Blogs so far ...