Blog Archives

Classic ASP VB Filter File Name Extensions From String EndsWith

Came across a classic ASP VB site recently in my adventures. There was a feature request to filter out some file extensions from existing code logic, and I discovered quickly most of my .Net methods were unavailable, so I came up with this little snippet and had a great blast from the past. :)

   function FilterExtensions(fn)
   FilterExtensions=true
   a_ext = Array(".db",".db") 'place additional extensions here 
   for each ext in a_ext
      i = InStrRev(fn,ext)
   if i>0 then
   FilterExtensions=false
   end if
   next
   end function

If FilterExtensions returns true then there were no matches (extension of filename successfully passed all filters).

call parent page from user control to invoke page methods

To illustrate how we will accomplish this using Reflections, we will be using repeater in a user control within a page.

Your repeater loads data easily within the user control code behind, but you want to utilize the “ItemCommand” event of the repeater to update some values on the page page.

Here’s how this can work:

Parent Page:

//the name doesn't have to match the corresponding method on user control but makes code more readable
    public void rptRepeaterName_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {

        try
        {
            if (e.CommandName == "commandname")
            {
               //do some work on data then call update on parent page to reload data and show within a modal

                ParentPage_UpdatePanel.Update();
                ParentPage_ModalPopup.Show();

            }
        }
        catch (Exception ex)
        { 
//do something
            throw new ApplicationException(ex.ToString());
        }

    }

User Control:

    protected void rptRepeaterName_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        MethodInfo mi = this.Page.GetType().GetMethod("rptRepeaterName_ItemCommand", BindingFlags.Public | BindingFlags.Instance);

//note we specify parent page as the object and pass in a new object representing our repeater and carrying its parameters
        if (mi!=null) mi.Invoke(this.Page, new Object[] {sender,e });

    }

Voila! Behold the power of Reflections! 8)

In particular, one of the references below (thanks Bruce Barker!) helped me come to this answer, however, the exact code he presents will result in a “Non-static method requires a target” error.

To avoid this error, make sure you always pass in the object when invoking a method that is non-static (within a class that is instantiated).

To learn more about reflections and how it works search my blog for other examples, and visit MSDN for a good overview.

References
Velocity Reviews, http://www.velocityreviews.com/forums/t71075-invoke-methods-on-the-parent-page-from-the-user-control.html
Reflection Overview (MSDN), http://msdn.microsoft.com/en-us/library/f7ykdhsy%28v=vs.71%29.aspx

Call Cancel from Custom Action in .Net Windows Installer Project

As an alternative to using the “Rollback” or “InstallException” approach, simply use pinvoke/interop to call the cancel button on the base installer form directly.

(see my related post for more detail and full code)

ShowWindow(msiwindowhandle, ShowWindowCommands.Show);
                IntPtr cancelbuttonhandle;
                const int BM_CLICK = 0x00F5;
                msiwindowhandle = FindWindow("#32770", InstallTitle);
                cancelbuttonhandle = FindWindowEx(msiwindowhandle, IntPtr.Zero, "Button", "Cancel");
                SetActiveWindow(msiwindowhandle); //necessary for button click to fire
                SendMessage(cancelbuttonhandle, BM_CLICK, IntPtr.Zero, IntPtr.Zero);

References
http://ronniediaz.com/2011/06/20/the-savedstate-dictionary-does-not-contain-the-expected-values-and-might-have-been-corrupted/

Calendar Extender Highlight Current Day in C# .Net

Thanks goes to Karan from asp.net blogs.

 <asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="tbTarget1"
                                PopupButtonID="btnCalendar" CssClass="calendarposition" OnClientShowing="currentdateactive">
                            </asp:CalendarExtender>
    function currentdateactive(e) {
        if (!e.get_selectedDate() || !e.get_element().value)
            e._selectedDate = (new Date()).getDateOnly();
    }
.ajax__calendar_active{background-color:#820024;color:#ffffff;border:1px solid #D4D0C8;}

/*use your own class to control positioning. careful of nested relative/absolute divs*/
.calendarposition{position:absolute;margin-top:250px;margin-left:250px;background-color:#fff;border:1px solid silver;}

/*prepend css class with div to override ms ajax web.resx autogenerated css*/
div.ajax__calendar_day{text-align:center;}

References
ASP.Net (blogs), http://weblogs.asp.net/karan/archive/2010/09/20/calendar-extender-today-s-date.aspx

Get Selected Item from ListBox in Winforms C# and VB .Net

Iterate through all items:

  foreach(ListItem item in ListBox1.Items)
    {
       if (item.Selected == True)
       {
          //item.Value //no to be confused with text
          //item.Text //text displayed on UI
       }
    }

Find specific item text:

  private string GetSelectedItem(ListBox container)
        {
            //string selecteditem = "";
            for (int i = 0; i < container.Items.Count; i++)
            {
                if (container.Items[i].Selected == true)
                {
                    //use .value alternatively if you are trying to get value instead of text
                    return ListBox1.Items[i].Text; //breaks the loop or
                    //break; //if you decide to use without a function
                }
            }
            return ""; //error handled in calling func, remove return value if used without a function
            //return selecteditem ; //if you want to iterate all items anyway
        }

More generalized for re-usability to get text or value, though a little less readable and alot more code:

private static class GetSelectedItem {
private enum ListBox_ContentType {
Text,
Value
}

public string Text(ListBox container) { Get_ContentType(container,ListBox_ContentType.Text);}
public string Value(ListBox container) { Get_ContentType(container,ListBox_ContentType.Value);}

private string Get_ContentType(ListBox container, ListBox_ContentType ContentType) {
  for (int i = 0; i < container.Items.Count; i++)
            {
                if (container.Items[i].Selected == true)
                {
if (ContentType == ListBox_ContentType.Value) {
return ListBox1.Items[i].Text;
}
else //ContentType == ListBox_ContentType.Value 
{
                    return ListBox1.Items[i].Value;
}
                }
            }
            return "";
}
}

C# and VB Equivalents

VB:

'shorthand object constructors; assigned initial properties
dim p as New Person() With {.FirstName = "john", .LastName="smith"}

'add handler for events
AddHandler context.BeginRequest, AddressOf Applicaton_BeginRequest

C#:

//shorthand object constructors; assigned initial properties
Person p = new Person() with {FirstName = "john", LastName="smith"}

//add handler for events
context.BeginRequest += Application_BeginRequest;

Serialize and Deserialize classes and objects in .Net

Serialization is a powerful tool and a major factor in many intermediate development technologies such as webservices.

Simply call “SerializeObject” and pass in the class name of your object for the “T” parameters, and your object will be serialized as an xml string which can then be stored in DB or written to disk!

To mark a public variable so it is not serialized, such as a decrypted key value or password, simply mark it with the attribute [XmlIgnore].

Enjoy. ;)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ApplicationName
{

    /// <summary>
    /// Contains generic static/shared methods accessible throughout the site
    /// </summary>
    public static class XMLSerialization
    {
        /// <summary>
        /// Serialize Object of Type T to XML and return value as string.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pObject"></param>
        /// <returns></returns>
        public static String SerializeObject<T>(T pObject)
        {
            /*try
            */
            String XmlizedString = null;
            MemoryStream memoryStream = new MemoryStream();
            XmlSerializer xs = new XmlSerializer(typeof(T));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            xs.Serialize(xmlTextWriter, pObject);
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
            return XmlizedString;
            /*}
            catch (Exception e) { System.Console.WriteLine(e); return null; }*/
        }

        public static T DeserializeObject<T>(string URL)
        {
            /*try
            */
            T returnObject;
            XmlSerializer xs = new XmlSerializer(typeof(T));
            XmlTextReader xmlTextReader = new XmlTextReader(URL);
            returnObject = (T)xs.Deserialize(xmlTextReader);
            //xs.Serialize(xmlTextWriter, pObject);
            return returnObject;
            /*}
            catch (Exception e) { System.Console.WriteLine(e); return null; }*/
        }

        public static String UTF8ByteArrayToString(Byte[] characters)
        {

            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        public static Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }
    }
}


Note:
Any snippets may have been condensed from their original sources for brevity. See references for original articles.

All server side code examples are in C# .Net.

References
Original reference misplaced.

.Net Thread Safety

Any future posts regarding thread safe calls will go here.

C#: (field)

//place in an event handling label, on edit, click, update, etc
    if(label1.InvokeRequired)
    {
        label1.Invoke(new MethodInvoker(delegate 
{ 
label1.text = "value"; 
}
));
    }
else
{
label1.text = "value"; 
}

C#: (singleton)

public sealed class ObjType
{
    private static ObjType _ObjInstance;
    private static readonly object objlock;

    ObjType()
    {
_ObjInstance=null;
objlock = new object();
    }

    public static ObjType ObjInstance
    {
        get
        {
            lock (objlock)
            {
                if (_ObjInstance==null)
                {
                    _ObjInstance= new Singleton();
                }
                return _ObjInstance;
            }
        }
    }
}

URL Encode in .Net

C#: (ASP .Net)

System.Web.HttpUtility.UrlEncode()

C#: (Client/Server Environment)

Uri.EscapeUriString()

References
MSDN, WebUtility Classhttp://msdn.microsoft.com/en-us/library/system.net.webutility.aspx
MSDN, Uri Classhttp://msdn.microsoft.com/en-us/library/system.uri.escapeuristring.aspx
MSDN blogs, http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx

Quick .Net Encryption Reference

The code below represents a very basic .NET encryption class which has been tested and should work in your application – simply plug and play. :)

Contains two static methods that can be called without needing to instantiate the class.

Keep in mind the initialization vector below (indicated by rgbIV) is generic, and you will need to come up with your own. Remember not to share this. Even if the password is compromised, the attacker would also need to know the initialization vector to crack your value.

Also note the code which has been commented out. This illustrates cases where passwords and/or IV can be statically set in the class and/or shared based on value passed in for password parameter.

Sharing IV and password or storing either statically is a security risk and could cause errors depending on byte differences of the values. If you statically store these values, you will still create secure cipher text, but it will be much easier to crack.

Enjoy. ;)

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace AIS.Common.Crypto
{

public static class Rijndael
{
    public static string Encrypt(string ClearText,string password)
    {

        byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

        MemoryStream ms = new MemoryStream();
        
        byte[] rgbIV = Encoding.ASCII.GetBytes("example");
        //byte[] key = Encoding.ASCII.GetBytes("longerexample");

        //byte[] rgbIV = Encoding.ASCII.GetBytes(password);
        byte[] key = Encoding.ASCII.GetBytes(password);

        CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV),
   CryptoStreamMode.Write);

        cs.Write(clearTextBytes, 0, clearTextBytes.Length);

        cs.Close();

        return Convert.ToBase64String(ms.ToArray());
    }

    public static string Decrypt(string EncryptedText, string password)
    {
        byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

        MemoryStream ms = new MemoryStream();

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();


        byte[] rgbIV = Encoding.ASCII.GetBytes("example");
        //byte[] key = Encoding.ASCII.GetBytes("longerexample");

        //byte[] rgbIV = Encoding.ASCII.GetBytes(password);
        byte[] key = Encoding.ASCII.GetBytes(password);

        CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),
        CryptoStreamMode.Write);

        cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);

        cs.Close();

        return Encoding.UTF8.GetString(ms.ToArray());

    }

}
}

References:
Wikipedia – Encryption, http://en.wikipedia.org/wiki/Encryption

Follow

Get every new post delivered to your Inbox.