50% OFF!!!

Booking.com

Tuesday, November 10, 2009

Asp.Net - Make short ids for controls

Here is a code for making your controls names/ids shorten than it is, because asp.net as default make every control name: {parent-id}_{control-id} and it makes html code length larger...


public class BasePage : Page
{
protected override void OnInit(EventArgs p_eventArgs)
{
MakeIdsShorted(this, true);
base.OnInit(p_eventArgs);
}

private int currentId = 0;
private void MakeIdsShorted(Control p_ctrl, bool p_recursive)
{
if (p_ctrl is Login)
{
return; // ignore ASP.Login controls
}
if (string.IsNullOrEmpty(p_ctrl.ID) == false)
{
//this.EnsureID();
p_ctrl.ID = "c" + currentId; // p_ctrl.ID.GetHashCode();
currentId++;
}

if (p_recursive == true)
{
foreach (Control c in p_ctrl.Controls)
{
MakeIdsShorted(c, true);
}
}
}
}



Make sure your created page is inherits from BasePage...
:)

Tuesday, October 20, 2009

Excel - Copy table to one column

This article copy table to one column, i.e. convert multiple columns into one column!
(after the operation, it also allows to remove empty cells)
also allow to convert multiple columns into more than one column!

This tutorial tested and found working on:
* Microsoft Office Excel 2003 with help of: Microsoft Office Word 2003
* Microsoft Office Excel 2007 with help of: Microsoft Office Word 2007


Instructions (WORKING TUTORIAL):
1. we have an excel file that contains table with data.
2. select all table data and press COPY (Ctrl + C)
3. open new Word document (Tested on Microsoft Office Word 2003)
4. PASTE (Ctrl + V) the copied table into word document.
5. Select the table (in word document) and select MENU: Table > Convert > Table to Text
[Microsoft Office Word 2007: Data (or View, should be last one) Group > Convert to Text]
Table selection using     icon
6. Set a character that not exists in the table (for example |)
7. Keep the text selected and press on MENU: Table > Convert > Text to Table
[Microsoft Office Word 2007: Insert Group > Table > Convert Text to Table]
8. Set number of columns = 1
9. Notice that the character is still | (that we selected)
10. Press OK
11. Now we have table with 1 column (and it is selected!)
12. Select entire table and press COPY (Ctrl + C)
Table selection using     icon
13. Open new EXCEL file (or use the original file)
14. PASTE (Ctrl + V) the table.
15. NOW you have 1 Column table!!!

Hope it helped you...
:)

Thursday, September 3, 2009

J2ME | Binary search algorithem


Binary search algorithem method/function for j2me platform.
Use is with sorted String array!!!
Enjoy... this works great with my example on J2ME | String array sort. link here.



public static int binarySearch(String[] p_arraySorted, String p_key)
{
return binarySearch(p_arraySorted, 0, p_arraySorted.length, p_key);
}



public static int binarySearch(String[] p_arraySorted, int p_first, int p_upto, String p_key)
{
int compare, mid;
while (p_first < p_upto)
{
// Compute mid point.
mid = (p_first + p_upto) / 2;

compare = p_key.compareTo(p_arraySorted[mid]);
if (compare < 0) // p_key < p_arraySorted[mid]
{
// repeat search in bottom half
p_upto = mid;
}
else if (compare > 0) // p_key > p_arraySorted[mid]
{
// Repeat search in top half
p_first = mid + 1;
}
else
{
// Found it. return position
return mid;
}
}

// Failed to find key
return -1;
}


Sort it and search it wisely...

J2ME | String array sort

Here is a good function for sorting string arrays.
The algorithem is BUBBLE-SORT algorithm.
The algorithem sorts the string array (dictionary comparison)


static void bubbleSort(String[] p_array) throws Exception
{
boolean anyCellSorted;
int length = p_array.length;
String tmp;
for (int i = length; --i >= 0;)
{
anyCellSorted = false;
for (int j = 0; j < i; j++)
{
if (p_array[j].compareTo(p_array[j + 1]) > 0)
{
tmp = p_array[j];
p_array[j] = p_array[j + 1];
p_array[j + 1] = tmp;
anyCellSorted = true;
}

}
if (anyCellSorted == false)
{
return;
}
}
}



if you want i will upload more SORT algorithems...

Friday, August 28, 2009

J2ME String Split method

Here is my code for splitting a string under Java - J2ME.
this is very helpfull for using a string array instead of string manipulation.

This is the best & fastest splitting method

Code:

public static String[] split(String p_text, String p_seperator)
{
Vector vecStrings = new Vector();

int index;
int prevIdx = 0;

while ((index = p_text.indexOf(p_seperator, prevIdx)) > -1)
{
vecStrings.addElement(p_text.substring(prevIdx, index));
prevIdx = index + 1;
}
vecStrings.addElement(p_text.substring(prevIdx));

String[] result = new String[vecStrings.size()];
vecStrings.copyInto(result);

return result;
}

Monday, July 6, 2009

Javascript html date control (validation)


Here is a sample code for an html input date control include DATE validation!
I searched a lot for such method for integration with PHP page but was little difficult.

Here is the HTML CODE:
<input id="inputDate1" name="Field1" value="21/07/2006" type="text" onblur="validateDate(this, '/')" maxlength="10">

<button onclick="setTodayDate(this.previousSibling, '/')">today</button>



Here is the JAVASCRIPT CODE:
function validateDate(p_inputObj, delim)
{
var text = p_inputObj.value;
var errorMsgs = "Following error(s) :\n";
var isDateCorrect = true;

var delim1 = text.indexOf(delim);
var delim2 = text.indexOf(delim, delim1+1);
if (delim2 <= delim1)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Must be in format of dd/mm/yyyy like (21/09/2008)\n";
}
else
{
var day = parseInt(text.substring(0, delim1), 10);
var splitter1 = text.substring(delim1, delim1+1);
var month = parseInt(text.substring(delim1+1, delim2), 10);
var splitter2 = text.substring(delim2, delim2+1);
var year = parseInt(text.substring(delim2+1), 10);

if (isNaN(day) || isNaN(month) || isNaN(year))
{
isDateCorrect = false;
if (isNaN(day)) { errorMsgs = errorMsgs + "- Day not in correct format!\n"; }
if (isNaN(month)) { errorMsgs = errorMsgs + "- Month not in correct format!\n"; }
if (isNaN(year)) { errorMsgs = errorMsgs + "- Year not in correct format!\n"; }
}
else
{
if (day<1)
{
errorMsgs = errorMsgs + "- Day must be between grater than 0\n";
isDateCorrect = false;
}

if (month>12 || month<1)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Month must be between 01 to 12\n";
}
else
{
if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12 )
{
if (day>31)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 31\n";
isDateCorrect = false;
}
}
else if(month==2)
{
// is leap year
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
if (day>29)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 29\n";
isDateCorrect = false;
}
}
else
{
if (day>28)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 28\n";
isDateCorrect = false;
}
}
}
else
{
if (day>30)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 30\n";
isDateCorrect = false;
}
}
}

if (year<2000)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Year not valid. must be more than 2000!\n";
}
else if (year>9999)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Year must be 4 digits!\n";
}
}
}

if (isDateCorrect == true)
{
var newStr = (day<10 ? '0' : '') + day + delim +
(month<10 ? '0' : '') + month + delim +
year; // +" "+hour+":"+minute+" "+AMPM;
p_inputObj.title = '';
var date = new Date();
date.setFullYear(year, month-1, day);
p_inputObj.dateVal = date;
p_inputObj.value = newStr;
p_inputObj.style.backgroundColor='#FFFFFF';
return true;
}
else
{
//alert(errorMsgs);
errorMsgs = errorMsgs.substring(0, errorMsgs.length-1);
p_inputObj.dateVal = null;
p_inputObj.title = errorMsgs;
p_inputObj.style.backgroundColor='#ffaaaa';
p_inputObj.focus();
return false;
}
}

function setTodayDate(p_inputObj, p_delim)
{
var dtNow = new Date();
var day = dtNow.getDate();
var month = dtNow.getMonth() + 1;
var year = dtNow.getFullYear();
p_inputObj.value = (day<10 ? '0' : '') + day + p_delim +
(month<10 ? '0' : '') + month + p_delim +
year;
}


Date format if dd/MM/yyyy but it can also be MM/dd/yy or yyyy!
Enjoy... :)

Tuesday, June 23, 2009

Html (& javascript) Slider example


Here is an example for html slider - Only using HTML & Javascript.
Nice animated slider (good looking animation)

Code:
<html>
<head>
<style>
.spltr {width: 4px; background-color: firebrick;}
</style>
<script language="javascript" type="text/javascript">
function scrollSpeedAdd(obj,step)
{
scrollStop();
scrollAdd(obj, scrollAdd.step + step);
}
function scrollAdd(obj,step)
{
scrollAdd.elem = document.getElementById('MainSlideDiv');
if(scrollAdd.elem)
{
scrollAdd.step = step;
scrollAdd.I = window.setInterval(startScroll,10);
}
}
function startScroll()
{
scrollAdd.elem.scrollLeft = scrollAdd.elem.scrollLeft + scrollAdd.step;
}
function scrollStop()
{
window.clearInterval(scrollAdd.I);
}
</script>
</head>
<body
<b>Set your mouse over the arrows...</b><br /><br />
<table width="700" border="0" cellspacing="0" cellpadding="0" bgcolor="khaki">
<tr style="text-align: center;">
<td width="30" onmouseout="scrollStop();" onmouseover="scrollAdd(this,-2)" onclick="scrollSpeedAdd(this,-1)"> << </td>
<td width="640" align="center">
<div style="overflow:hidden; width:630; height:55;" id="MainSlideDiv" dir="rtl">
<table width="100%" style="text-align:center" border="0" cellspacing="5" cellpadding="5">
<tr>
<td>Test 1111 </td>
<td class="spltr"> </td>
<td>Test 2222 </td>
<td class="spltr"> </td>
<td>Test 3333 </td>
<td class="spltr"> </td>
<td>Test 4444 </td>
<td class="spltr"> </td>
<td>Test 5555 </td>
<td class="spltr"> </td>
<td>Test 6666 </td>
<td class="spltr"> </td>
<td>Test 7777 </td>
<td class="spltr"> </td>
<td>Test 8888 </td>
<td class="spltr"> </td>
<td>Test 9999 </td>
<td class="spltr"> </td>
<td>Test AAAA </td>
<td class="spltr"> </td>
<td>Test BBBB </td>
<td class="spltr"> </td>
<td>Test CCCC </td>
<td class="spltr"> </td>
<td>Test DDDD </td>
<td class="spltr"> </td>
<td>Test EEEE </td>
<td class="spltr"> </td>
<td>Test FFFF </td>
<td class="spltr"> </td>
</tr>
</table>
</div>
</td>
<td width="30" onmouseout="scrollStop()" onmouseover="scrollAdd(this,2)" onclick="scrollSpeedAdd(this,+1)"> >> </td>
</tr>
</table>
</body>
</html>

Thursday, June 18, 2009

Working with sql xml | Sql server


Here is a code for manipulating XML object under SQL Server.
This code allow to recieve attribute and note contents.
Best for xml manipulations.

--Under this configuration:
DECLARE @xml XML
SET @xml = '<root><a><b id="456"></b><c>world...</c></a></root>'


--Get attribute's content from xml field:
SELECT @xml.value('(//root/a/b/@id)[1]','int') AS 'Attribute Content'


--Get node's content from xml field:
SELECT @xml.value('(//root/a/c)[1]','nvarchar(MAX)') AS 'Node Content'




Bits and bitwise operation in C#


Here is an example for bits string format and bitwise opertaion (not).
It helps us to print the number as bit representation.

Example (using console application):
using System;
class MainClass
{
static void Main()
{
int[] values = { 0, 0x111, 0xfffff, 0x8888, 0x22000022};
foreach (int v in values)
{
Console.WriteLine("~0x{0:x8} = 0x{1:x8}", v, ~v);
}
}
}


Output:
~0x00000000 = 0xffffffff
~0x00000111 = 0xfffffeee
~0x000fffff = 0xfff00000
~0x00008888 = 0xffff7777
~0x22000022 = 0xddffffdd


Helpful for "bits users" which deal with common bit operations...


Source: http://msdn.microsoft.com/en-us/library/d2bd4x66(VS.80).aspx

Tuesday, June 16, 2009

J2ME | Analog Clock control - custom item



Here is an example for anlogic clock control (extends CustomItem) which may be added to Form class and also in Canvas class.
for Form class just add it as and item,
and for Canvas class and its paint method, provide graphics to AnalogClock's paint method.

Here is Code for the analog clock:


package CustomItems;

import javax.microedition.lcdui.*;
import java.util.Calendar;

public class AnalogClock extends CustomItem implements Runnable
{

private double diam = 0.38;
private double LineLengthSeconds = 0.90;
private double LineLengthMinutes = 0.75;
private double LineLengthHour = 0.50;
private double LineLengthTicks = 0.08;
private double TextPositionRelativeR = 1.22;
//
/***
* Represents control's width
*/
private int Width = 100;
/***
* Represents control's height
*/
private int Height = 100;
/***
* Represents clock's radius
*/
private int _raduis;
/***
* Represents clock's center point - X
*/
private int _circleCenterX;
/***
* Represents clock's center point - Y
*/
private int _circleCenterY;
/***
* Represents clock's current date&time
*/
private Calendar _now;
/***
* Represents the thread which implement the clock's ticks
*/
private Thread _thread = null;
/***
* Represents a flag which describe if the thread is running or not
*/
private boolean _threadIsRunning = false;
//
/***
* Represents the background color of the clock
*/
public int BackColor = 0xffffff;
/***
* Represents the color of the clock (text & lines)
*/
public int ClockColor = 0x000000;
/***
* A flag which represent whether or not display the date inside the clock
*/
public boolean ShowDate = false;
/***
* Represents the font of the text drawn
*/
public Font Font;

/** Creates a new instance of AnalogClock */
public AnalogClock(String p_label, int p_size)
{
super(p_label);
if (p_size <= 0)
{
sizeChanged(Width, Height);
}
else
{
sizeChanged(p_size, p_size);
}
Font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_SMALL);
}

protected int getMinContentWidth()
{
return 10;
}

protected int getMinContentHeight()
{
return 10;
}

protected int getPrefContentWidth(int p_height)
{
return Width;
}

protected int getPrefContentHeight(int p_width)
{
return Height;
}

protected void sizeChanged(int p_w, int p_h)
{
Height = p_h;
Width = p_w;
int size = Math.min(Width, Height);
_raduis = (int) (diam * (double) size);
_circleCenterX = size / 2;
_circleCenterY = size / 2;
_now = Calendar.getInstance();
}

private int pointX(double minute, double radius, int _circleCenterX)
{
double angle = minute * Math.PI / 30.0;
return (int) ((double) _circleCenterX + radius * Math.sin(angle));
}

private int pointY(double minute, double radius, int oy)
{
double angle = minute * Math.PI / 30.0;
return (int) ((double) oy - radius * Math.cos(angle));
}

public void updateTime()
{
_now = Calendar.getInstance();
repaint();
}

public void updateTime(Calendar p_currtime)
{
_now = p_currtime;
repaint();
}

protected void paint(Graphics g, int w, int h)
{
// clear background
g.setColor(BackColor);
g.fillRect(0, 0, Width - 1, Height - 1);
g.setColor(ClockColor);

// draw circle
g.drawArc(_circleCenterX - _raduis, _circleCenterY - _raduis, _raduis * 2, _raduis * 2, 0, 360);

// set text's font
g.setFont(Font);
int textH = Font.getHeight();

// draw date (if allowed)
if (ShowDate == true)
{
String strDate = getDateString(_now, "-");
int strDateWidth = Font.stringWidth(strDate);
g.drawRect(_circleCenterX - strDateWidth / 2, _circleCenterY, strDateWidth, textH);
g.drawString(strDate, _circleCenterX, _circleCenterY, Graphics.TOP | Graphics.HCENTER);
}

// draw ticks & digits
int textW;
for (int hour = 1; hour <= 12; hour++)
{
double angle = hour * 60.0 / 12.0;
g.drawLine(
pointX(angle, _raduis * (1 - LineLengthTicks), _circleCenterX),
pointY(angle, _raduis * (1 - LineLengthTicks), _circleCenterY),
pointX(angle, _raduis, _circleCenterX),
pointY(angle, _raduis, _circleCenterY));

// texts
textW = Font.stringWidth("" + hour);
g.drawString("" + hour,
(int) pointX(angle, _raduis * TextPositionRelativeR, _circleCenterX) - textW / 2,
(int) pointY(angle, _raduis * TextPositionRelativeR, _circleCenterY) - textH / 2,
0);
}

double hour = _now.get(Calendar.HOUR) * 60.0 / 12.0;
double minute = _now.get(Calendar.MINUTE);
double second = _now.get(Calendar.SECOND);

// draw hour line
g.drawLine(_circleCenterX, _circleCenterY,
pointX(hour + (double) minute / 12.0, _raduis * LineLengthHour, _circleCenterX),
pointY(hour + (double) minute / 12.0, _raduis * LineLengthHour, _circleCenterY));

// draw minutes line
g.drawLine(_circleCenterX, _circleCenterY,
pointX(minute + second / 60.0, _raduis * LineLengthMinutes, _circleCenterX),
pointY(minute + second / 60.0, _raduis * LineLengthMinutes, _circleCenterY));

// draw seconds line
g.drawLine(_circleCenterX, _circleCenterY,
pointX((double) second, _raduis * LineLengthSeconds, _circleCenterX),
pointY((double) second, _raduis * LineLengthSeconds, _circleCenterY));
}

public synchronized void startTicking()
{
if (_thread == null)
{
_thread = new Thread(this);

_threadIsRunning = true;
_thread.start();
}
}

public synchronized void stopTicking()
{
if (_thread != null)
{
_threadIsRunning = false;
try
{
_thread.join();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}

public void run()
{
while (_threadIsRunning == true)
{
this.updateTime();

try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}

private String getDateString(Calendar p_calendar, String p_delimiter)
{
int day = p_calendar.get(Calendar.DAY_OF_MONTH);
int month = p_calendar.get(Calendar.MONTH) + 1;
int year = p_calendar.get(Calendar.YEAR);

String strDay = (day < 10) ? "0" + day : String.valueOf(day);
String strMonth = (month < 10) ? "0" + month : String.valueOf(month);
String strYear = String.valueOf(year);

StringBuffer sb = new StringBuffer();
sb.append(strDay);
sb.append(p_delimiter);
sb.append(strMonth);
sb.append(p_delimiter);
sb.append(strYear);

return sb.toString();
}
}


Usage sample:

package Test;

import CustomItems.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class StartMidlet extends MIDlet implements CommandListener
{
public void startApp()
{
Form f = new Form("My Clock Test");
int w = f.getWidth();
int h = f.getHeight();

AnalogClock cl = new AnalogClock(null, (int) (w * 0.8));
cl.setLayout(Item.LAYOUT_2 | Item.LAYOUT_CENTER);
cl.startTicking();
f.append(cl);

Command cmd = new Command("Back", Command.BACK, 0);
f.addCommand(cmd);

cmd = new Command("Next", Command.OK, 1);
f.addCommand(cmd);

f.setCommandListener(this);

Display.getDisplay(this).setCurrent(f);
}

public void pauseApp()
{ }

public void destroyApp(boolean unconditional)
{ }

public void commandAction(Command arg0, Displayable arg1)
{ }
}




The contorl have 2 methods for managing clock timer.
startTicking - for start ticking the timer (this calls repaint...)
stopTicking- for stop the timer



Use it smartly...

Thursday, June 11, 2009

Sql Server | Check if exist: DataBase, Table or Stored-Procedure

Here is a code for checking if an object exist in SQL SERVER.
This may be helpful if you have 2 enviroments and on each one of them
the object (db, table, stored-procedure) are diffrent,
so you can check whether this is the specific db and perform actions...

Check is Database exists:

if db_id('dbname') is not null



Check is Table exists:

if object_id('object_name', 'U') is not null -- for table



Check is Store-Procedure exists:

if object_id('object_name', 'P') is not null -- for SP



hope this is helps...

Monday, June 8, 2009

J2ME | String Replace method



I found a good string replace function/method.
J2ME do not contain string replace (only char replace),
so this method is very helpful!!!



public static String replace(String _text, String _searchStr, String _replacementStr) {
// String buffer to store str
StringBuffer sb = new StringBuffer();

// Search for search
int searchStringPos = _text.indexOf(_searchStr);
int startPos = 0;
int searchStringLength = _searchStr.length();

// Iterate to add string
while (searchStringPos != -1) {
sb.append(_text.substring(startPos, searchStringPos)).append(_replacementStr);
startPos = searchStringPos + searchStringLength;
searchStringPos = _text.indexOf(_searchStr, startPos);
}

// Create string
sb.append(_text.substring(startPos,_text.length()));

return sb.toString();
}





found at http://forums.sun.com/thread.jspa?threadID=734604&tstart=5431

Thursday, June 4, 2009

Sql Server | Compare 2 tables columns


Here is a sql statement for comapring two tables (may be in diffrent DBs) columns.
This SQL statement compare only if column exist in both or not and return the difference.
You may improve the sql statement for comapring more... :)
I hope this sql script will be helpful...



DECLARE @Db1 NVARCHAR(MAX)
DECLARE @Table1 NVARCHAR(MAX)
DECLARE @Db2 NVARCHAR(MAX)
DECLARE @Table2 NVARCHAR(MAX)
DECLARE @Sql NVARCHAR(MAX)

SET @Db1 = 'MMIS_SNAP'
SET @Table1 = 'CodeTablesData'
SET @Db2 = 'MMIS_SNAP'
SET @Table2 = 'CodeTables'
SET @Sql = ' ' +
' SELECT ''in ' + @Db1 + '.' + @Table1 + ' --- not in ' + @Db2 + '.' + @Table2 + ''' AS TITLE, a.TABLE_CATALOG, a.column_name ' +
' FROM ' + @Db1 + '.INFORMATION_SCHEMA.COLUMNS a ' +
' WHERE a.column_name NOT IN (SELECT column_name ' +
' FROM ' + @Db2 + '.INFORMATION_SCHEMA.COLUMNS b ' +
' WHERE b.table_name IN (''' + @Table2 + ''')) ' +
' AND a.table_name IN (''' + @Table1 + ''') ' +

' UNION ALL ' +

' SELECT ''in ' + @Db2 + '.' + @Table2 + ' --- not in ' + @Db1 + '.' + @Table1 + ''' AS TITLE, a.TABLE_CATALOG, a.column_name ' +
' FROM ' + @Db2 + '.INFORMATION_SCHEMA.COLUMNS a ' +
' WHERE a.column_name NOT IN (SELECT column_name ' +
' FROM ' + @Db1 + '.INFORMATION_SCHEMA.COLUMNS b ' +
' WHERE b.table_name IN (''' + @Table1 + ''')) ' +
' AND a.table_name IN (''' + @Table2 + ''') ' +
''

EXEC (@Sql)




You may create store-procedure from this script, and the automaticly run it
on all your tables.
This may be automatic table columns comparison...


post your additional information as comments, thanks


ANOTHER SAMPLE, faster compare with 'Allow null' & 'Data type':



SET @Db1 = 'TestDB'
SET @Table1 = 'Users'
SET @Db2 = 'TestDB'
SET @Table2 = 'Users2'

SET @Sql = ' ' +
' SELECT ''in ' + @Db1 + '.' + @Table1 + ' --- not in ' + @Db2 + '.' + @Table2 + ''' AS TITLE, ' +
' a.TABLE_CATALOG, ' +
' a.COLUMN_NAME, ' +
' a.IS_NULLABLE, ' +
' a.DATA_TYPE ' +
' FROM ' + @Db1 + '.INFORMATION_SCHEMA.COLUMNS a ' +
' WHERE NOT EXISTS ( ' +
' SELECT b.COLUMN_NAME ' +
' FROM ' + @Db2 + '.INFORMATION_SCHEMA.COLUMNS b ' +
' WHERE b.table_name IN (''' + @Table2 + ''') ' +
' AND b.COLUMN_NAME = a.COLUMN_NAME ' +
' AND b.IS_NULLABLE = a.IS_NULLABLE ' +
' AND b.DATA_TYPE = a.DATA_TYPE ' +
' ) ' +
' AND a.table_name IN (''' + @Table1 + ''') ' +
' ' +
' UNION ALL ' +
' ' +
' SELECT ''in ' + @Db2 + '.' + @Table2 + ' --- not in ' + @Db1 + '.' + @Table1 + ''' AS TITLE, ' +
' a.TABLE_CATALOG, ' +
' a.COLUMN_NAME, ' +
' a.IS_NULLABLE, ' +
' a.DATA_TYPE ' +
' FROM ' + @Db2 + '.INFORMATION_SCHEMA.COLUMNS a ' +
' WHERE NOT EXISTS ( ' +
' SELECT b.COLUMN_NAME ' +
' FROM ' + @Db1 + '.INFORMATION_SCHEMA.COLUMNS b ' +
' WHERE b.table_name IN (''' + @Table1 + ''') ' +
' AND b.COLUMN_NAME = a.COLUMN_NAME ' +
' AND b.IS_NULLABLE = a.IS_NULLABLE ' +
' AND b.DATA_TYPE = a.DATA_TYPE ' +
' ) ' +
' AND a.table_name IN (''' + @Table2 + ''') ' +
' '

PRINT @Sql
EXEC (@Sql)



Monday, April 6, 2009

Compact Framework | debugger and monitoring

.NET Compact Framework Power Toys 3.5

The Power Toys for .NET Compact Framework 3.5 provides several tools for evaluating performance, obtaining diagnostic information, configuring and working with the .NET Compact Framework.


The Tools
NETCF CLR Profiler – CLR Profiler is an instrumenting allocation profiler for NETCF applications. It provides detailed allocation visualizations, allocation callstacks and other views of the managed heap for diagnosing various memory management issues.
NETCF ServiceModel Metadata Tool – The .NET Compact Framework ServiceModel Metadata Tool (netcfsvcutil.exe) allows you to generate a Windows Communication Foundation (WCF) client proxy to help developers consume WCF services on device. Like svcutil.exe, which is the desktop version of the utility, netcfsvcutil.exe is a command-line tool that generates service model code from metadata documents and generates metadata documents from service model code.
App Configuration Tool - On-device tool for specifying what version of NETCF an application will run against (ie. Create config file), displaying installed versions of NETCF and displaying info about DLLs in the GAC.
Remote Logging Configuration Tool– The Logging Configuration Tool enables users to easily configure logging options on a NETCF device including: loader, interop, network, error and finalizer logs. (used to be a part of RPM)
Remote Performance Monitor and GC Heap Viewer – Provides real time counter data (ranging from Garbage Collector activity to type loading info) on a running NETCF application. The GC Heap Viewer feature allows you to capture the managed heap at any moment your app is running to view live references, and allows you to compare multiple snapshots to find memory leaks.
NETCF Network Log Viewer – A utility for viewing NETCF network log data.

download link:

http://www.microsoft.com/downloads/details.aspx?FamilyID=c8174c14-a27d-4148-bf01-86c2e0953eab&displaylang=en

Tuesday, March 24, 2009

C# | Asp.Net | Convert DataTable to Excel File



C# | Asp.Net | Convert DataTable to Excel File

Here is an example, to convert fro existing DataTable to Excel file

Working fine to me...
Tested on Excel 2003 and partially on Excel 2007 :)




///
/// Converts excel file sheet content into DataTable.
///

///
///
///
public static DataTable ExcelFileToDataTable(string p_fileUrl, int p_sheetIndex)
{
DataTable dbSchema = new DataTable();
DataSet dataSet = new DataSet();
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + p_fileUrl + ";" + "Extended Properties=Excel 8.0;Mode=Read;";

using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();

// Get all sheetnames from an excel file into data table
dbSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

string sheetName = dbSchema.Rows[p_sheetIndex]["TABLE_NAME"].ToString();
string selectCommandText = string.Format("SELECT * FROM [{0}]", sheetName);

using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommandText, conn))
{
adapter.Fill(dataSet);
}

return dataSet.Tables[0];
}
}

///
/// Converts DataTable to Excel-File
///

///
///
///
///
public static bool DataTableToExcelFile(DataTable p_dt, string p_filePath, EventHandler p_onRowHandled)
{
try
{
// fix table name
if (p_dt.TableName == "" || p_dt.TableName.Equals("Table", StringComparison.OrdinalIgnoreCase) == true)
{
p_dt.TableName = "NONAME";
}

// fix file path name
if (p_filePath.EndsWith(".xls") == false)
{
p_filePath += ".xls";
}

// insure file not exist!
System.IO.FileInfo fi = new System.IO.FileInfo(p_filePath);
if (fi.Name.Replace(".xls", "").Trim().Length <= 0)
{
p_filePath = p_filePath.Replace(".xls", p_dt.TableName + ".xls");
}
if (System.IO.File.Exists(p_filePath))
{
System.IO.File.Delete(p_filePath);
}

using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + p_filePath + ";Extended Properties=Excel 8.0"))
{
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = con;
con.Open();

// create table
command.CommandText = GenerateSqlStatementCreateTable(p_dt);
command.ExecuteNonQuery();

DataRow dr;
OleDbParameter oleDbParameter;

// Create columns & values (as parameters) script
string columns, parameters;
GenerateColumnsString(p_dt, out columns, out parameters);

for (int i = 0; i < p_dt.Rows.Count; i++)
{
dr = p_dt.Rows[i];

// set insert statement parameters
command.Parameters.Clear();
for (int j = 0; j < p_dt.Columns.Count; j++)
{
oleDbParameter = new OleDbParameter();
oleDbParameter.ParameterName = "@p" + j;

if (dr.IsNull(j) == true)
{
oleDbParameter.Value = DBNull.Value;
}
else
{
oleDbParameter.Value = dr[j];
}
command.Parameters.Add(oleDbParameter);
}

command.CommandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2})", p_dt.TableName, columns, parameters);
command.ExecuteNonQuery();

// Perform step...
if (p_onRowHandled != null)
{
p_onRowHandled(p_dt, EventArgs.Empty);
}
}
}

con.Close();
}
return true;
}
catch (Exception ex)
{
throw (ex);
}
}


///
/// Generates columns names string delimited by commas
/// also supply parameters for the given columns, for example:
///
/// out string p_columns = [columnname0],[columnname1],[columnname2]
/// out string p_params = @p0, @p1, @p2
///

///

///
///
///
private static void GenerateColumnsString(DataTable p_dt, out string p_columns, out string p_params)
{
StringBuilder sbColumns = new StringBuilder();
StringBuilder sbParams = new StringBuilder();
for (int i = 0; i < p_dt.Columns.Count; i++)
{
if (i != 0)
{
sbColumns.Append(',');
sbParams.Append(',');
}
sbColumns.AppendFormat("[{0}]", p_dt.Columns[i].ColumnName);
sbParams.AppendFormat("@p{0}", i);
}

p_columns = sbColumns.ToString();
p_params = sbParams.ToString();
}

///
/// Create SQL-Script for creating table which represent the given DataTable
///

///
///
private static string GenerateSqlStatementCreateTable(DataTable p_dt)
{
StringBuilder sbCreateTable = new StringBuilder();

DataColumn dc;
sbCreateTable.AppendFormat("CREATE TABLE {0} (", p_dt.TableName);
for (int i = 0; i < p_dt.Columns.Count; i++)
{
dc = p_dt.Columns[i];
if (i != 0)
{
sbCreateTable.Append(",");
}

string dataType = dc.DataType.Equals(typeof(double)) ? "DOUBLE" : "NVARCHAR";

sbCreateTable.AppendFormat("[{0}] {1}", dc.ColumnName, dataType);
}
sbCreateTable.Append(")");

return sbCreateTable.ToString();
}



Monday, January 12, 2009

Javascript | Restrict number of open windows



Javascript Restrict number of open windows

here is a javascript code which allows:

  • Check if window is open
  • List open windows
  • Manage 5 open windows (Any amount)
  • Open restricted num. of windows.







function openWindowMAX5(p_url)
{
var win_I;
for(var i=0; i<5; i++)
{
win_I = window.open('', 'win_' + i);
if (win_I.document.location.href == 'about:blank')
{
window.status = 'win_'+i;
win_I = window.open(p_url, 'win_' + i);
break;
}
}
event.returnValue = false;
return false;
}


Used html code:
Open on new window

Tested on:

Working: IE7, CHROME 1.0.154

Not Working: Mozilla Firefox 3.0