Thursday, March 12, 2009

get data from excel using linq .net

You might want to read excel file and import the data from the excel into your .net application. Therefore you need a service that provide you this functionality. Here is the class that you can use it.

I suggest you to import the data and store into a DataTable and from there you can start to manipulate it. You can also use a linq to query the data. Is that simple and easy?

Initialization
PrivatePropertyExcel ppe;
DataTable currentExcelDataTable;

private void btnTestConnection_Click(object sender, EventArgs e)
{
try
{
if (openFileDialog1.ShowDialog() == DialogResult.OK && txtSheetName.Text != "")
{

ppe = new PrivatePropertyExcel(openFileDialog1.FileName, txtSheetName.Text);
currentExcelDataTable = ppe.ExcelProvider.GetDataTable();
gridSource.DataSource = currentExcelDataTable;
gridTarget.DataSource = null;


btnValidate.Enabled = true;
txtStatus.Text = "";
}
else
{
if (txtSheetName.Text == "")
{
MessageBox.Show("Please enter sheet name");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}


Calling function
public List<string> GetPropertyType(int columnIndex)
{
List<string> propertyTypeList = new List<string>();

var propertyTypes =
(from e in ppe.ExcelProvider
where e.GetString(columnIndex).Trim() != ""
select e.GetString(columnIndex).Trim()).Distinct();

foreach (string pt in propertyTypes)
{
if (!propertyTypeList.Contains(pt))
{
propertyTypeList.Add(pt);
}
}

return propertyTypeList;
}


Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Collections;
using System.Data;

namespace ReplicatorServices
{
public class ExcelRow
{
List<object> columns;

public ExcelRow()
{
columns = new List<object>();
}

internal void AddColumn(object value)
{
columns.Add(value);
}

public object this[int index]
{
get { return columns[index]; }
}

public string GetString(int index)
{
if (columns[index] is DBNull)
{
return null;
}
return columns[index].ToString();
}

public int Count
{
get { return this.columns.Count; }
}
}

public class ExcelProvider:IEnumerable<ExcelRow>
{
private string sheet;
private string filePath;
private List<ExcelRow> rows;
private string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties= ""Excel 8.0;HDR=YES;""";

public ExcelProvider()
{
rows = new List<ExcelRow>();
}

public static ExcelProvider Create(string filePath, string sheet)
{
ExcelProvider provider = new ExcelProvider();
provider.sheet = sheet;
provider.filePath = filePath;
return provider;
}

public DataTable GetDataTable()
{
DataTable dt= new DataTable();
connectionString = string.Format(connectionString, filePath);
rows.Clear();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select DISTINCT * from [" + sheet + "$] ";
using (OleDbDataReader reader = cmd.ExecuteReader())
{
dt.Load(reader);
}
}
}

return dt;
}

public DataTable GetDataTable(string sqlCommand)
{
DataTable dt = new DataTable();
connectionString = string.Format(connectionString, filePath);
rows.Clear();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sqlCommand;
using (OleDbDataReader reader = cmd.ExecuteReader())
{
dt.Load(reader);
}
}
}

return dt;
}
public List<string> GetColumnsName()
{
List<string> columnlist = new List<string>();
connectionString = string.Format(connectionString, filePath);
rows.Clear();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from [" + sheet + "$]";
using (OleDbDataReader reader = cmd.ExecuteReader())
{
for (int i = 0; i < reader.FieldCount; i++)
{
columnlist.Add(reader.GetName(i).Trim());
}
}
}
}

return columnlist;
}

private void Load()
{
connectionString = string.Format(connectionString, filePath);
rows.Clear();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from [" + sheet + "$]";
using (OleDbDataReader reader = cmd.ExecuteReader())
{

while (reader.Read())
{
ExcelRow newRow = new ExcelRow();
for(int count = 0; count < reader.FieldCount; count++) {
newRow.AddColumn(reader[count]);
}
rows.Add(newRow);
}
}
}
}
}

public IEnumerator<ExcelRow> GetEnumerator()
{
Load();
return rows.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
Load();
return rows.GetEnumerator();
}

}
}

Get html tag using regex .net

Let say you want to get a specific tag from the html, you need to use regex to scan and grab it. here is the example :)


private string FixedImgHtml(string html, int fixedwidth)
{
string input = html;
MatchCollection mc = Regex.Matches(input, "<img[a-zA-Z0-9_\\^\\$\\.\\\\{\\[\\}\\]\\(\\)\\*\\+\\?\\\\~`!@#%&-=;:'\",/\\n\\s]*>", RegexOptions.IgnoreCase);
foreach (Match m in mc)
{
input = input.Replace(m.Value, m.Value + " onload='AutoImageResizing(this, "+ fixedwidth.ToString()+")'");
}
return input;
}

Friday, March 6, 2009

dynamic sql generated column using data

Sometimes we want dynamically create a column by using data and not having table structure. You can do it having this sql statement

select *, LFV1.Description as DevName,LFV2.Description as Location
from
listing L
LEFT OUTER JOIN ListingFieldValue LFV1 ON L.ListingID =
LFV1.ListingID AND LFV1.ListingFieldTypeID = '1'
LEFT OUTER JOIN
ListingFieldValue LFV2 ON L.ListingID = LFV2.ListingID AND
LFV2.ListingFieldTypeID = '2'
WHERE L.listingid = 1

Friday, February 27, 2009

using jquery to create check box for each item

if you want to create a check box each of the item with toggle functionality use this code snippet

<script type="text/javascript">
$(document).ready(function() {

$("#<%=btnSendEnquiryList.ClientID%>").click(function(event) {
var hasItemSelected = false;
$("#<%=dlNewDev.ClientID%> :checkbox").attr("checked", function() {
if ($(this).attr("checked") == true) {
hasItemSelected = true;
$(this).preventDefault();
} else {
hasItemSelected = false;
}
});


if (hasItemSelected == false) {
alert("There is no listing selected. Please select at least 1 listing.");
return false;
}
});

$("#<%=chkCheckedAll.ClientID%>").click(function() {
$("#<%=dlNewDev.ClientID%> :checkbox").attr("checked", function() {
if ($(this).attr("checked") != true) {
$(this).attr("checked", "checked")
} else {
$(this).removeAttr("checked")
}
});

});

});
</script>

set/get selected value from select option / dropdownlist using jquery

Here is an example of how to set/get selected value from select option / dropdownlist using jquery

To get a selected value

var selectedItemText = $('#<%=ddlCurrency.ClientID%>
option:selected').val();


To set an option value to be selected

$('#<%=ddlLocation.ClientID%> option:contains(' + location +
')').attr("selected", true);

Wednesday, February 25, 2009

Failed to load viewstate.

if you encounter this error


Failed to load viewstate. The control tree into which viewstate is being loaded
must match the control tree that was used to save viewstate during the previous
request. For example, when adding controls dynamically, the controls added
during a post-back


Make sure the related control is set to false

EnableViewState="false"



Create thumbnail image using jquery or javascript

If you want to maintain the proportion of the image when creating thumbnail for your website, please use this tested script

<script src="js/jquery-1.2.6.min.js"
type="text/javascript"></script>
<style
type="text/css">
.thumbnail
{
vertical-align:middle;
}
</style>
<script type="text/javascript" >
$(document).ready(
function AutoImageResizing(src, fixedSize) {
var
width = src.width;
var height = src.height;
var ratio = width / height;
if (width > fixedSize) {
src.width = fixedSize

}
if
(height > fixedSize) {
var sizedwidth = fixedSize / ratio;
var
sizedheight = fixedSize / ratio;
if (height > width) {
if (height
> sizedwidth) {
src.height = fixedSize
}
if (sizedwidth
> fixedSize) {
src.width = src.width * ratio;
} else {
src.height = src.height * ratio;
}
} else {
src.width =
fixedSize
}
}
}
);
</script>
HTML


<img class="thumbnail"
src="http://latimesblogs.latimes.com/photos/uncategorized/2008/10/05/love.jpg"
onload="AutoImageResizing(this,100)" />
<img class="thumbnail"
src="http://images.google.com.my/intl/en_ALL/images/images_hp.gif"
onload="AutoImageResizing(this,100)"/>



Do you find this useful, please let me know! :)