C#: Get Parent Control with Generics

I use the following method to return a parent control of a specific type. This method is recursive and uses generics.

<br />
private Control GetParentControl(Control control)<br />
{<br />
if (control.Parent.GetType() == typeof(T1))<br />
{<br />
return control.Parent;<br />
}<br />
else<br />
{<br />
return GetParentControl(control.Parent);<br />
}<br />
}</p>
<p>

Create a Visual Studio add-in with contextmenu and selected text as input

Create a Visual Studio add-in with contextmenu and selected text as input

When working with a new way of storing settings in a database. I was frustrated how much work it was to check the value of setting from code. So I deceided to make my life a bit easier by creating a VS2008 contextmenu add-in. With this add-in I can select text within VS and use the value of the selected text within the add-in popup. The hardest part was figuring out how to create a contextmenu and how to use the selected text as input value.

In this blogpost I will show how to create a Visual Studio contextmenu add-in and pass the selected text to the pop-up. I’m not going to explain how to create an add-in you can easily find articles about this on MSDN or blogs (just try Google).

Now let’s get started. Create an new Visual Studio add-in project and add the following code to the OnConnetion Method within the Connect.cs. This code will insert add the contextmenu.


_applicationObject = (DTE2)application;
CommandBars cBars = (CommandBars)_applicationObject.CommandBars;

CommandBar editorCommandBar = (CommandBar)cBars["Editor Context Menus"];
CommandBarPopup editPopUp = (CommandBarPopup)editorCommandBar.Controls["Code Window"];

Command command = commands.AddNamedCommand2(_addInInstance,
 "GetSetting", "Bekijk Setting", "Executes the command for test", true, 733, ref contextGUIDS,
 (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,
 (int)vsCommandStyle.vsCommandStylePictAndText,
 vsCommandControlType.vsCommandControlTypeButton);

Then to get the selected text I use the following method within the Exec of the Connect.cs and pass the selected text (return value) to a property of a Windows Form pop-up.


private string GetSelection()
{
    string setting = "";

    //Check active document
    if (_applicationObject.ActiveDocument != null)
    {
        //Get active document
        TextDocument objTextDocument = (TextDocument)_applicationObject.ActiveDocument.Object("");
        TextSelection objTextSelection = objTextDocument.Selection;

        if (!String.IsNullOrEmpty(objTextSelection.Text))
        {
 //Get selected text
            setting = objTextSelection.Text;
        }
    }
    return setting;
}

Hope it helps.

Cheers,
Pieter

Asp.Net: DataPager problem with Listview

When using the Datapager with a ListView I had the following problem. When clicking a paging button for the first time nothing happens.But when I click a button the second time, then the page from the first click loads.

I search the internet for a solution and found that you need to add some code to the OnPagePropertiesChanging event of the list view to reload the DataPager.

The following code is the solution to my problem. Including a fix that the data doesn’t get loaded two times.


private List productList;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        fillGrid();
}

private void fillGrid()
{
    if(productList == null)
        productList = getproducts();
    ListView1.DataSource = productList;
    ListView1.DataBind();
    DataPager1.DataBind();
}

public List getproducts()
{
    using (AdventureWrksDataContext db = new AdventureWrksDataContext())
    {
        return db.Products.ToList();
    }
}

protected void lvproducts_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
    DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
    fillGrid();
}


You can download the solution (PagingExample.zip (83.05 kb))

Cheers,

Pieter

Add meta data (keywords, description) dynamicly

Add meta-data dynamically to your page by adding a HtmlMeta control to your Header. In this example I dynamically add a keyword string to the page.


string keyWords = "metatags, html, dynamic, generate";

HtmlMeta keywords = new HtmlMeta();
keywords.Name = "keywords";
keywords.Content = keyWords;
Page.Header.Controls.Add(keywords); 


You can do the same for other meta-data like description.

Using the ViewState within the SelectMethod of a ObjectDataSource

By default it is not possible to use the ViewState within methods of a ObjectDataSource. Because the DataSource doesn’t run within the current page instance, it just fires the method that you specified.

You can set the page instance for the DataSourceby setting the ObjectInstance property in the ObjectCreating event of the DataSource.


&lt;asp:ObjectDataSource ID=&quot;odsListing&quot; runat=&quot;server&quot; SelectMethod=&quot;getItems&quot; TypeName=&quot;YOUR.NAMESPACE&quot; OnObjectCreating=&quot;ObjectDataSource_ObjectCreating&quot; DataObjectTypeName=&quot;List"&gt;



protected void ObjectDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
 e.ObjectInstance = this;
}


Now you can use the ViewState in you DataSourceMethod (getItems() in this example).

Asp.Net: Clear inputfields after form submit

Every time a form is successful summited I need to clear all input-fields to the default values and give feedback to the user. I wrote a method ClearControl that can have a control as input parameter. This method will set the control based on his type back to the defaultvalue.


 public static void ClearControl(Control control)
{
 switch (control.GetType().Name)
 {
  case "TextBox":
   TextBox txtBox = (TextBox)control;
   txtBox.Text = "";
   break;
  case "DropDownList":
   DropDownList ddl = (DropDownList)control;
   ddl.SelectedIndex = 0;
   break;
  case "CheckBox":
   CheckBox chk = (CheckBox)control;
   chk.Checked = false;
   break;
  case "CheckBoxList":
   CheckBoxList chkList = (CheckBoxList)control;
   foreach (ListItem li in chkList.Items)
    li.Selected = false;
   break;
  case "Panel":
   ClearFields((Panel)control);
   break;
  case "RadioButtonList":
   RadioButtonList rbl = (RadioButtonList)control;
   rbl.SelectedIndex = -1;
   break;
 }
}


To use this method I wrote a method ‘ClearFields’ that accepts a View or Container control. You can add every type of control that has the .Controls property.


public static void ClearFields(Panel container)
{
 foreach (Control control in container.Controls)
 {
  ClearControl(control);
 }
}

public static void ClearFields(View container)
{
 foreach (Control control in container.Controls)
 {
  ClearControl(control);
 }
}


When I have some time left I will try to implement the ClearFields Method as a ExtensionMethod.

Cheers,

Pieter

Sitecore: itemlist with ObjectDataSource, Listview and DataPager

For a new project I started working with Sitecore again.

I needed to create a listing of items with paging. I implemented a Listview with a ObjectDataSource and the DataPager control.




    
         <li class="clearfix">
            <a class="thumb" ID="thumnailLink"> 
                
            </a>
            <h2></a></h2>
            <span class="date">  </span>
            
            
     </li>
    
    
        Geen artikelen
    
    
        <ul ID="itemPlaceholderContainer">
            <li ID="itemPlaceholder" />
        </ul>
    
    
        <br />
    


<ul>
  <li class="paging">
        
         
             
                
             
         
        
    </li>
</ul> 





In the code behind I created the public method GetItems which returns a ChildListCollection.


namespace MyNameSpace
{
    public partial class MyUsercontrol: System.Web.UI.UserControl
    {
     
       public Sitecore.Collections.ChildList GetItems()
       {
          return Sitecore.Context.Item.GetChildren();
        }
     }
} 


The PagedControlID property of the datapager control is set to the ID of the Listview.