Monday, July 30, 2012

.NET Mathematics


Loading UserControl on another UserControl & assigning Properties of loaded UserControl

Parent UserControl (.ascx) UI:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MultiVarientModule.ascx.cs"
    Inherits="Modules.MultiVarientModule" %>
<div id="parent" runat="server">
</div>


Parent UserControl Code File (.cs) :

#region CONSTANTS
const string CAROUSAL = "~/Modules/Carousal.ascx";
const string THREECOLUMNS = "~/Modules/ThreeColumn.ascx";
const string REGULAR = "~/Modules/Regular.ascx";
#endregion
protected void Page_Load(object sender, EventArgs e)
{
switch(ControlName)
{
       case "Carousel":
              parent.Controls.Add(LoadControl(CAROUSAL));
              break;
       case "ThreeColumn":
              parent.Controls.Add(LoadControl(THREECOLUMNS));
              break;
       case "Regular":
              {
              Regular reg = (Regular)LoadControl(REGULAR);
              reg.DisplayMode = ControlName;
              reg.DisplayItem = multiVarientItem;
              parent.Controls.Add(reg);
              break;
              }
       default:
              break;
}
}


The above code is showing three different usercontrols to be added in parent div of another usercontrol.


For assigning value to properties of child usercontrol, we have to write mentioned code. Here "Regular" is one userControl.

Regular reg = (Regular)LoadControl(REGULAR);
reg.DisplayMode = ControlName;
reg.DisplayItem = multiVarientItem;
parent.Controls.Add(reg);
break;


Loading the usercontrol and assigning it to Regular class
     Regular reg = (Regular)LoadControl(REGULAR);


Assigning properties of regular class 

     reg.DisplayMode = ControlName;
     reg.DisplayItem = multiVarientItem;

and finally adding the object to parent usercontrol.

Regular (.ascx) UI
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Regular.ascx.cs" Inherits="Modules.Regular" %>
<div>
    <h4><asp:Literal ID="regularTitle" runat="server" /></h4>
</div>
<div class="leftInteriorTwoColumn" runat="server" id="LinkWithDescription">
<span sizcache="30" sizset="126">
<asp:Repeater ID="Repeater_LinkWithDescription" runat="server" OnItemDataBound="Repeater_LinkWithDescription_ItemDataBound">
<ItemTemplate>
  <a runat="server" id="articleLink" />
  <div sizcache="30" sizset="127">
  <div class="editorsContent" sizcache="30" sizset="127">
  <p sizcache="30" sizset="127">
    <span id="publishedDate" runat="server" class="pubdate" />
    <span id="articleDescription" runat="server" />
    <a id="moreLink" runat="server" class="moreLink">more</a>
  </p>
  </div>
  </div>
</ItemTemplate>
</asp:Repeater>
</span>
</div>


Regular (.cs) Code File:
private string displayMode = String.Empty;
public string DisplayMode
{
  get
  {
    return displayMode;
  }
  set
  {
    displayMode = value;
  }
}

private Item displayItem;
public Item DisplayItem
{
  get
  {
    return displayItem;
  }
  set
  {
    displayItem = value;
  }
}


Wednesday, June 6, 2012

Gridview Performance improvement with Custom Paging


Gridview provides excellent features to show the data on webpage. Few of the popular features are sorting, column arrangements, styles, item templates, editing, updating and deleting.

Get the data from SQL, DataList, Arrays and bind the data to Gridview and it displays the data in required format.

GridView1.DataSource = SQL command Result OR List() OR Array()
GridView1.Databind();

When the data is huge and you bind the data with GridView, it can impact the performance of your page. To Overcome that, GridView Paging is provided but it fetches all the records and bind it to GridView and when you click on page number, it shows the records of that page index.
GridView paging is also not good solution and hits the performance as it fetches all the records once and then bind it to GridView.

Here is the solution which do custom paging and fetches the data when required.

GridView with Custom Paging
GridView with Custom Paging



GridView is showing 10 records by default. Clicking on 'Next' button will show next 10 records. Clicking on 'Previous' button will show previous 10 records. First button will take you to First Page and Last button will take you to Last page of GridView.


Trick starts with SQL Server Stored Procedure. We have to write a stored procedure which will return the required records. 


SQL Paging to improve performance

A kind of SQL Paging is done which takes two parameters 
1. startIndex (from where to start)           
2. recordCount (how many records to fetch)


SQL Paging using Stored Procedure
SQL Paging using Stored Procedure
Default value of @startIndex is set to 0 and @recordCount is set to 10 which means it will fetch 10 records starting from 0th row.


Now time to write code to fetch the data and populate it to GridView.


Populate GridView on PageLoad


Here GridView is being populated on Page_Load method and PopulateData method is pulling the records from SQL Server.


PopulateData(GridView1.PageIndex, 10);
Note: GridView1.PageIndex gives the Index value which is 0 by Default


Next Button Click

Now when we will click on 'Next' Button, we will increment the GridView1.PageIndex by 1 and next 10 results will be shown.


Next Button Click Code Behind
Next Button Click Code Behind
PopulateData(GridView1.PageIndex * 10, 10);      
where GridView1.PageIndex is incremented by 1 and gives results as 1. Multiply by 10 will give result as 10. Now records will start from 10 and will display next 10 records.


Previous Button Click

Similarly Previous Button will decrement the GridView1.PageIndex by 1 on every click till the value is 0. 


First Button Click

Clicking on First button will call method 
PopulateData(0, 10); 

Last Button Click

Clicking on Last button will call method 
PopulateData(TotalRecordCount()-10, TotalRecordCount());  
where TotalRecordCount() method returns total count of records in sql table.


After doing Cutom Paging, Editing, Deleting and Updating can also be done on fetched records.


GridView Edit / Delete / Update after Custom Paging

Editing can also be done easily after doing custom paging.


It is very much similar to editing we do in Gridview. The only difference is that we are 
calling method PopulateData after finding index of edited row in GridView.


PopulateData(GridView1.PageIndex*10,10)


The reason we are calling this method because if  we will not call this method how GridView will come to know which record to edit when page postback will happen on click on Edit button of GridView.


GridView Edit after Custom Paging
GridView Edit after Custom Paging


As we have written the code for Edit, similarly you can write the code for cancel, delete and update event of GridView.

Happy Coding !!




It would be honor for me if you could provide your valuable comments if you liked / not  liked /suggestions to improve.

Wednesday, May 30, 2012

Wrap the data in Gridview

Sometime the data in Gridview column is large and it makes the scrollbar to appear on the page. Due to which User Interface of page get effected.

Here are two solutions for achieving the required wrapping.

Why two solution are provided?
The reason is that sometime solution 1 doesn't work for all browser. It vary with the way how you are pulling the data in Gridview.

Solution 1:
Putting <ItemStyle> tag and setting the width of column.
Wrapping the data using <ItemStyle> tag
Wrapping the data using <ItemStyle> tag

Solution 2:
Putting <div> tag and styling on bounded column (Works on all browsers)

Wrapping the data using <div> tag and styling
Wrapping the data using <div> tag and styling


Output: 
Here is the output how data displayed in Gridview is wrapped.

Gridview Wrapping
Gridview wrapping








Keep posting your queries to get optimum solution.

Tuesday, May 29, 2012

System.BadImageFormatException

Could not load file or assembly 'System.Data.SQLite' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly 'System.Data.SQLite' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Source Error:An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Data.SQLite' could not be loaded.


System.BadImageFormatException
System.BadImageFormatException: System.Data.SQLite


Resolution Steps:


1. Goto IIS (inetmgr)
2. Open Application Pools
3. Select the required pool
4. Click on 'Advanced Settings' on right hand side panal
5. Check the 'Enable 32-bit Applications' and set it to true (see below screenshot)
6. Restart the pool and browse your website

IIS Setting
Application Pool Advanced Settings


Wednesday, May 9, 2012

Sitecore Best Practices


Design Prospective:
1. Put components statically in html if it is being used multiple times and not much changes required. Use placeholders only to bind those components which are getting change frequently.
2. Always set presentation details on _standard values.
3. Do appropriate image resizing on server else it will slow down the performance when opening on browse.
4. Create template for providing data to presentation component.
5. Get the Data from DataSource from component Parameters to get variations.

Code Prospective:
1. Test your html/css/javascript code in such a way that Page Editor is enable for edit by non technical staff.
2. Given meaningful names to placeholder so that right component could add under right placeholder.
3. Write code using C# coz this is language generally use by Sitecore Support team.
Use GUID instead of path/name as content can be moved to some other location in content tree.
4. Create separate config file for your component instead of adding directly in web.config.
5. Use Lucene Search in case data is large
6. Do customization(if required) carefully and properly tested as it can impact the performance.


Friday, May 4, 2012

Sitecore customization using pipelines


A pipeline consists of a number of processors arranged in sequence to process a common set of parameters. If I have a series of tasks, which need to be performed to accomplish a task, then a pipeline may be the way to go.
Instead of passing to each processor an arguments object containing these parameters, the pipeline class itself exposes properties representing the parameters.
Sitecore pipelines also allow an object to pass through each step. This object can be manipulated by any of the steps and passed through to the next step until the end is reached and the object can be used by whatever executed the pipeline in the first place.
In configuration file, you will be able to see numbers of pipelines, which is default from sitecore. You can create your own custom code and add pipeline to execute that code.
Example:

Pipeline contains parameter ‘type’, which contains information about class and assembly as shown in snapshot.


UI customization using pipelines
Each step in pipeline is called a ‘processor’. Pipeline call the ‘Process’ method from class. Whatever functionality you want to achieve can be written in ‘Process’ method.

For Example:
In this scenario, Pipeline class is inheriting ‘HttpRequestProcessor’ and overriding its Process method to achieve some functionality.


Now code has been written, we have to add pipeline in ‘web.config’ so it could execute. We have added our custom pipeline next to step, where we want to it be executed.


So with just a few lines of code and configuration we can consume benefits of pipeline architecture and perform our custom actions.

Have a great day and enjoy coding !!

Thursday, March 1, 2012

Google Recaptcha implementation without plugin



Google Recaptcha Implementation

STEP 1:

Add Following Script on you page:

<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js">

script>

<script src="http://code.jquery.com/jquery-latest.pack.js">script>

<script type="text/javascript">

function showRecaptcha(element) {

Recaptcha.create("your_public_key", element, { theme: "clean", callback: Recaptcha.focus_response_field });

}

function showResult() {

//alert('start');

var challengeVal = Recaptcha.get_challenge();

//alert(challengeVal);

var reponseVal = Recaptcha.get_response();

alert(reponseVal);

var remoteIp = "172.18.224.92";

//alert(remoteIp);

var privateKey = ’Your_Private_Key’;

var requestUrl = "http://api-verify.recaptcha.net/verify?privatekey=" + privateKey + "&remoteip=" + remoteIp + "&challenge=" + challengeVal + "&response=" + reponseVal;

return requestUrl;

}

script>

<script type="text/javascript">

$(document).ready(function () {

var container = $('#target');

$('.ajaxtrigger').click(function () {

var url = showResult();

doAjax(url);

//return false;

});

function doAjax(url) {

// if it is an external URI

if (url.match('^http')) {

// call YQL

$.getJSON("http://query.yahooapis.com/v1/public/yql?" +

"q=select%20*%20from%20html%20where%20url%3D%22" +

encodeURIComponent(url) +

"%22&format=xml'&callback=?",

// this function gets the data from the successful

// JSON-P call

function (data) {

// if there is data, filter it and render it out

if (data.results[0]) {

var data = filterData(data.results[0]);

container.html(data);

Recaptcha.reload();

// otherwise tell the world that something went wrong

} else {

var errormsg = '

Error: could not load the page.

';

container.html(errormsg);

}

}

);

// if it is not an external URI, use Ajax load()

} else {

$('#target').load(url);

}

}

// filter out some nasties

// filter out some nasties

function filterData(data) {

return data;

}

});

script>


After adding above script, add following line of code in section to display recaptcha

STEP 2:

<div id="recaptcha_div">

<script type="text/javascript">showRecaptcha('recaptcha_div');script>

div>

<input type="submit" name="Button1" value="Submit" class="ajaxtrigger">

<div id="target">div>