http://chandigarh.quikr.com/domestic-call-center-job-BPO-Call-Center-KPO/domestic-call-center-job/x379
Monday, December 5, 2011
Friday, November 18, 2011
database layer
--- ExecuteNonQuery
public static int ExecuteNonQuery(DbCommand command)
{
// The number of affected rows
int affectedRows = -1;
// Execute the command making sure the connection gets closed in the end
try
{
// Open the connection of the command
command.Connection.Open();
// Execute the command and get the number of affected rows
affectedRows = command.ExecuteNonQuery();
}
catch (Exception ex)
{
(ex.Message, ex);
}
finally
{
command.Connection.Close();
}
// return the number of affected rows
return affectedRows;
}
public static string ExecuteScalar(DbCommand command)
{
// The value to be returned
string value = String.Empty;
// Execute the command making sure the connection gets closed in the end
try
{
// Open the connection of the command
command.Connection.Open();
// Execute the command and get the number of affected rows
var val = command.ExecuteScalar();
if(val != null)
value = val.ToString();
}
catch (Exception ex)
{
(ex.Message, ex);
}
finally
{
command.Connection.Close();
}
// return the result
return value;
}
public static IDataReader ExecuteSelectReaderCommand(DbCommand command)
{
DbDataReader reader;
// Execute the command making sure the connection gets closed in the end
try
{
// Open the data connection
command.Connection.Open();
command.CommandTimeout = 600;
// Execute the command and save the results in a DataTable
reader = command.ExecuteReader();
}
catch (Exception ex)
{
///rethrow our exception wrapper to recognize it on the upper level
(ex.Message, ex);
}
finally
{
command.Connection.Close();
}
return reader;
}
public static int ExecuteNonQuery(DbCommand command)
{
// The number of affected rows
int affectedRows = -1;
// Execute the command making sure the connection gets closed in the end
try
{
// Open the connection of the command
command.Connection.Open();
// Execute the command and get the number of affected rows
affectedRows = command.ExecuteNonQuery();
}
catch (Exception ex)
{
(ex.Message, ex);
}
finally
{
command.Connection.Close();
}
// return the number of affected rows
return affectedRows;
}
public static string ExecuteScalar(DbCommand command)
{
// The value to be returned
string value = String.Empty;
// Execute the command making sure the connection gets closed in the end
try
{
// Open the connection of the command
command.Connection.Open();
// Execute the command and get the number of affected rows
var val = command.ExecuteScalar();
if(val != null)
value = val.ToString();
}
catch (Exception ex)
{
(ex.Message, ex);
}
finally
{
command.Connection.Close();
}
// return the result
return value;
}
public static IDataReader ExecuteSelectReaderCommand(DbCommand command)
{
DbDataReader reader;
// Execute the command making sure the connection gets closed in the end
try
{
// Open the data connection
command.Connection.Open();
command.CommandTimeout = 600;
// Execute the command and save the results in a DataTable
reader = command.ExecuteReader();
}
catch (Exception ex)
{
///rethrow our exception wrapper to recognize it on the upper level
(ex.Message, ex);
}
finally
{
command.Connection.Close();
}
return reader;
}
grid view drop down event
Please refer to these url
1. http://asimsajjad.blogspot.com/2009/09/raising-dropdownlist.html
2.http://stackoverflow.com/questions/485390/why-isnt-the-selectedindexchanged-event-firing-from-a-dropdownlist-in-a-gridvie
1. http://asimsajjad.blogspot.com/2009/09/raising-dropdownlist.html
2.http://stackoverflow.com/questions/485390/why-isnt-the-selectedindexchanged-event-firing-from-a-dropdownlist-in-a-gridvie
Thursday, November 17, 2011
BINARY SEARCH in c++ with output
// Program to search an element from an array using BINARY SEARCH
#include
#include
int bsearch(int [],int,int);
int main()
{ int AR[50],ITEM,N,index;
clrscr();
cout<<"ENTER DESIRED ARRAY SIZE(MAX 50): " ;
cin>>N;
cout<<"\n ENTER ARRAY ELEMENTS(MUST BE STORED IN ASC ORDER)\n";
for(int i=0;i cin>>AR[i];
cout<<"\n ENTER ELEMENTS TO BE SEARCHED FOR:";
cin>>ITEM;
index=Bsearch(AR,N,ITEM);
if(index==-1)
cout<<"\n SORRY!!! GIVEN DATA CAN'T BE OPENED \n";
else
cout<<"\n ELEMENTS FOUND AT INDEX:"< <<"\t,Position:"< return 0; }
int bsearch(int AR[],int size ,int item)
{ int beg ,last,mid;
beg=0;
last=size-1;
while(beg<=last)
{ mid=(beg+last)/2;
if(item==AR[mid])
return mid;
else if(item>AR[mid])
beg=mid+1;
else
last=mid-1;
}
return -1;
}
===================:OUTPUT:===============================================
ENTER DESIRED ARRAY SIZE(MAX 50): 4
ENTER ARRAY ELEMENTS(MUST BE STORED IN ASC ORDER)
4
25
60
78
ENTER ELEMENTS TO BE SEARCHED FOR: 78
ELEMENTS FOUND AT INDEX:3 , POSITION:4
#include
#include
int bsearch(int [],int,int);
int main()
{ int AR[50],ITEM,N,index;
clrscr();
cout<<"ENTER DESIRED ARRAY SIZE(MAX 50): " ;
cin>>N;
cout<<"\n ENTER ARRAY ELEMENTS(MUST BE STORED IN ASC ORDER)\n";
for(int i=0;i cin>>AR[i];
cout<<"\n ENTER ELEMENTS TO BE SEARCHED FOR:";
cin>>ITEM;
index=Bsearch(AR,N,ITEM);
if(index==-1)
cout<<"\n SORRY!!! GIVEN DATA CAN'T BE OPENED \n";
else
cout<<"\n ELEMENTS FOUND AT INDEX:"< <<"\t,Position:"< return 0; }
int bsearch(int AR[],int size ,int item)
{ int beg ,last,mid;
beg=0;
last=size-1;
while(beg<=last)
{ mid=(beg+last)/2;
if(item==AR[mid])
return mid;
else if(item>AR[mid])
beg=mid+1;
else
last=mid-1;
}
return -1;
}
===================:OUTPUT:===============================================
ENTER DESIRED ARRAY SIZE(MAX 50): 4
ENTER ARRAY ELEMENTS(MUST BE STORED IN ASC ORDER)
4
25
60
78
ENTER ELEMENTS TO BE SEARCHED FOR: 78
ELEMENTS FOUND AT INDEX:3 , POSITION:4
Binary search in c with OUTPUT
#include<conio.h>
#include<stdio.h>
void main()
{
int n[50],i,j,k,temp,first,mid,last,ser,flag=0;
clrscr();
printf("how many number u want to insert?");
scanf("%d",&k);
for(i=0;i<=k-1;i++){
printf("Enter values?");
scanf("%d",&n[i]);
}
for(i=0;i<=k-1;i++){
for(j=i+1;j<=k-1;j++)
{
if(n[i]>n[j])
{
temp=n[i];
n[i]=n[j];
n[j]=temp;
}
}
}
printf("Sorting\n");
for(i=0;i<=k-1;i++){
printf("%d\n",n[i]);
}
printf("Enter serching number?");
scanf("%d",&ser);
first=0;
last=k-1;
mid=(first+last)/2;
while(last>=first)
{
if(ser==n[mid])
{
flag=1;
break;
}
else if(n[mid]>ser)
{
first=first;
last=mid-1;
mid=(first+last)/2;
}
else if(n[mid]<ser)
{
first=mid+1;
last=last;
mid=(first+last)/2;
}
}
if(flag==1){
printf("\n");
printf("SEARCHING NUMBER IS FOUND");
printf("\n");
printf(" POSITION OF SEARCHED NUMBER %d",mid+1);
}
else{
printf("Searching Number not found");
}
getch();
}
OUTPUT :
How many numbers u want to insert ? 5
Enter values ?22
Enter values ?34
Enter values ?6
Enter values ?78
Enter values ?44
Sorting :
6
22
34
44
78
#include<stdio.h>
void main()
{
int n[50],i,j,k,temp,first,mid,last,ser,flag=0;
clrscr();
printf("how many number u want to insert?");
scanf("%d",&k);
for(i=0;i<=k-1;i++){
printf("Enter values?");
scanf("%d",&n[i]);
}
for(i=0;i<=k-1;i++){
for(j=i+1;j<=k-1;j++)
{
if(n[i]>n[j])
{
temp=n[i];
n[i]=n[j];
n[j]=temp;
}
}
}
printf("Sorting\n");
for(i=0;i<=k-1;i++){
printf("%d\n",n[i]);
}
printf("Enter serching number?");
scanf("%d",&ser);
first=0;
last=k-1;
mid=(first+last)/2;
while(last>=first)
{
if(ser==n[mid])
{
flag=1;
break;
}
else if(n[mid]>ser)
{
first=first;
last=mid-1;
mid=(first+last)/2;
}
else if(n[mid]<ser)
{
first=mid+1;
last=last;
mid=(first+last)/2;
}
}
if(flag==1){
printf("\n");
printf("SEARCHING NUMBER IS FOUND");
printf("\n");
printf(" POSITION OF SEARCHED NUMBER %d",mid+1);
}
else{
printf("Searching Number not found");
}
getch();
}
OUTPUT :
How many numbers u want to insert ? 5
Enter values ?22
Enter values ?34
Enter values ?6
Enter values ?78
Enter values ?44
Sorting :
6
22
34
44
78
Tuesday, November 15, 2011
New Project
#include<iostream.h>
class searching
{
private:
double *array;
int n;
public:
void input();
void linearsearch();
};
void searching::input()
{
cout<<”*********************************…
<<”This program is to implement linear search algorithm\n”
<<”*************************************…
cout<<”Enter how many numbers you are going to enter::”;
cin>>n;
array=new double[n+1];
cout<<”Now enter your elements ::\n”;
for(int i=1;i<=n;i++)
cin>>array[i];
}
void searching::linearsearch()
{
cout<<”Enter the number to be searched ::”;
double x;
cin>>x;
int i;
for(i=1;i<=n;i++)
{
if(array[i]==x)
{
cout<<”found at position ::”<<i<<endl;
break;
}
}
if(i>n)
cout<<”Not found\n”;
}
int main()
{
searching obj;
obj.input();
obj.linearsearch();
return 0;
}
/************* Please not copy this************************…
SAMPLE OUTPUT ::
**************************************…
This program is to implement linear search algorithm
**************************************…
Enter how many numbers you are going to enter::5
Now enter your elements ::
1.1
1.2
1.3
1.4
1.5
Enter the number to be searched ::1.5
found at position ::5
Press any key to continue
//Binary Searching
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
int l_v=1;
int h_v;
int a[51];
int middle;
int num,i=0;
cout<<"Input your sorted num :
";
while(scanf("%d",&a[i])!=EOF)
i++;
h_v=i;
cout<<"
The input numbers are :
";
i=0;
while(i<h_v)
{
cout<<a[i]<<endl;
i++;
}
getch();
cout<<"
Input your searching number :
";
cin>>num;
for(int n=0;a[middle]!=num;n++)
{
middle = (l_v + h_v)/2;
if(a[middle]>num)
h_v = middle - 1;
else if(a[middle]<num)
l_v = middle + 1;
else if(a[middle]==num)
cout<<"
Found your number in "<<middle+1<<" position.";
}
cout<<"
This program's loop is executed "<<n<<" times to find out
the
number.";
getch();
}
Binary search program in C
#include <stdio.h>
int main()
{
int a[20] = {0};
int n, i, j, temp;
int *beg, *end, *mid, target;
printf(" enter the total integers you want to enter (make it less then 20):\n");
scanf("%d", &n);
if (n >= 20) return 0; // ouch!
printf(" enter the integer array elements:\n" );
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
// sort the loaded array, a must for binary search!
// you can apply qsort or other algorithms here
for(i = 0; i < n-1; i++)
{
for(j = 0; j < n-i-1; j++)
{
if (a[j+1] < a[j])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf(" the sorted numbers are:");
for(i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
// point to beginning and end of the array
beg = &a[0];
end = &a[n]; // use n = one element past the loaded array!
printf("\n beg points to address %d and end to %d",beg, end); // test
// mid should point somewhere in the middle of these addresses
mid = beg += n/2;
printf("\n mid points to address %d", mid); // test
printf("\n enter the number to be searched:");
scanf("%d",&target);
// binary search, there is an AND in the middle of while()!!!
while((beg <= end) && (*mid != target))
{
// is the target in lower or upper half?
if (target < *mid)
{
end = mid - 1; // new end
n = n/2;
mid = beg += n/2; // new middle
}
else
{
beg = mid + 1; // new beginning
n = n/2;
mid = beg += n/2; // new middle
}
}
// did you find the target?
if (*mid == target)
{
printf("\n %d found!", target);
}
else
{
printf("\n %d not found!", target);
}
getchar(); // trap enter
getchar(); // wait
return 0;
}
//----------- Java application-------------
Binary Search in Java
import java.util.*; public class BinarySearch { public static void main(String[] args) { int[] intArray = new int[10]; int searchValue = 0, index; System.out.println("Enter 10 numbers"); Scanner input = new Scanner(System.in); for (int i = 0; i < intArray.length; i++) { intArray[i] = input.nextInt(); } System.out.print("Enter a number to search for: "); searchValue = input.nextInt(); index = binarySearch(intArray, searchValue); if (index != -1) { System.out.println("Found at index: " + index); } else { System.out.println("Not Found"); } } static int binarySearch(int[] search, int find) { int start, end, midPt; start = 0; end = search.length - 1; while (start <= end) { midPt = (start + end) / 2; if (search[midPt] == find) { return midPt; } else if (search[midPt] < find) { start = midPt + 1; } else { end = midPt - 1; } } return -1; } }Output
Enter 10 numbers: 1 2 3 4 5 6 7 8 9 10 Enter a number to search for:5 Found at index: 4
Tuesday, November 8, 2011
Move items one listbox to 2nd listbox [using j query]
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#<%=btnMoveRight.ClientID %>').click(function ()
{
var selectedOptions = $('#<%=lstBox1.ClientID %> option:selected');
if (selectedOptions.length == 0) {
alert("Please select option to move");
return false;
}
$('#<%=lstBox2.ClientID %>').append($(selectedOptions).clone());
$(selectedOptions).remove();
return false;
});
$('#<%=btnMoveLeft.ClientID %>').click(function () {
var selectedOptions = $('#<%=lstBox2.ClientID %> option:selected');
if (selectedOptions.length == 0) {
alert("Please select option to move");
return false;
}
$('#<%=lstBox1.ClientID %>').append($(selectedOptions).clone());
$(selectedOptions).remove();
return false;
});
});
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="lstBox1" runat="server" SelectionMode="Multiple" Height="138px"
Width="108px">
<asp:ListItem Text="A" Value="1"></asp:ListItem>
<asp:ListItem Text="B" Value="2"></asp:ListItem>
<asp:ListItem Text="C" Value="3"></asp:ListItem>
<asp:ListItem Text="D" Value="4"></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
<asp:ListItem Text="4" Value="4"></asp:ListItem>
</asp:ListBox>
<asp:Button ID="btnMoveRight" runat="server" Text=">>" />
<asp:Button ID="btnMoveLeft" runat="server" Text="<<" />
<asp:ListBox ID="lstBox2" runat="server" SelectionMode="Multiple" Height="134px"
Width="104px">
<asp:ListItem Text="E" Value="5"></asp:ListItem>
<asp:ListItem Text="F" Value="6"></asp:ListItem>
<asp:ListItem Text="G" Value="7"></asp:ListItem>
<asp:ListItem Text="H" Value="8"></asp:ListItem>
</asp:ListBox>
</div>
</form>
</body>
</html>
<head runat="server">
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#<%=btnMoveRight.ClientID %>').click(function ()
{
var selectedOptions = $('#<%=lstBox1.ClientID %> option:selected');
if (selectedOptions.length == 0) {
alert("Please select option to move");
return false;
}
$('#<%=lstBox2.ClientID %>').append($(selectedOptions).clone());
$(selectedOptions).remove();
return false;
});
$('#<%=btnMoveLeft.ClientID %>').click(function () {
var selectedOptions = $('#<%=lstBox2.ClientID %> option:selected');
if (selectedOptions.length == 0) {
alert("Please select option to move");
return false;
}
$('#<%=lstBox1.ClientID %>').append($(selectedOptions).clone());
$(selectedOptions).remove();
return false;
});
});
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="lstBox1" runat="server" SelectionMode="Multiple" Height="138px"
Width="108px">
<asp:ListItem Text="A" Value="1"></asp:ListItem>
<asp:ListItem Text="B" Value="2"></asp:ListItem>
<asp:ListItem Text="C" Value="3"></asp:ListItem>
<asp:ListItem Text="D" Value="4"></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
<asp:ListItem Text="4" Value="4"></asp:ListItem>
</asp:ListBox>
<asp:Button ID="btnMoveRight" runat="server" Text=">>" />
<asp:Button ID="btnMoveLeft" runat="server" Text="<<" />
<asp:ListBox ID="lstBox2" runat="server" SelectionMode="Multiple" Height="134px"
Width="104px">
<asp:ListItem Text="E" Value="5"></asp:ListItem>
<asp:ListItem Text="F" Value="6"></asp:ListItem>
<asp:ListItem Text="G" Value="7"></asp:ListItem>
<asp:ListItem Text="H" Value="8"></asp:ListItem>
</asp:ListBox>
</div>
</form>
</body>
</html>
Tuesday, October 11, 2011
Hcl training
for meow
c interview:
1. http://www.mitkota.com/c-interview-questions-techpreparation.pdf
2.http://www.techinterviews.com/c-interview-questions-and-answers-3
C++ :
1. http://www.shettysoft.com/interview/C_C++_interview_questions_answers.htm
c interview:
1. http://www.mitkota.com/c-interview-questions-techpreparation.pdf
2.http://www.techinterviews.com/c-interview-questions-and-answers-3
C++ :
1. http://www.shettysoft.com/interview/C_C++_interview_questions_answers.htm
Sunday, October 9, 2011
Sql query for find the coloum name in whole database
Hi
Sql query for finding the colum name in whole database
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%move_id%'
ORDER BY schema_name, table_name
Sql query for finding the colum name in whole database
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%move_id%'
ORDER BY schema_name, table_name
Wednesday, October 5, 2011
Friday, September 30, 2011
binary and linear search program
http://in.answers.yahoo.com/question/index?qid=20101206082552AA0E0wS
Monday, September 19, 2011
Convert html to pdf using i text sharp
First u download the i text sharp dll from internet
and then
namespace
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.Collections;
using System.Text;
using System.Net;
using System.IO;
using System.Configuration;
//------- Function for generate pdf ---
private void newpdf()
{
Document doc = new Document(PageSize.A4);
DataTable dtPDFfile = new DataTable();
DataTable dt = new DataTable();
dt.Columns.Add("link", typeof(System.String));
dt.Columns.Add("Property_name", typeof(System.String));
dt.Columns.Add("Street_address", typeof(System.String));
dt.Columns.Add("walia", typeof(System.String));
for (Int32 i = 0; i < 30; i++)
{
DataRow dr = dt.NewRow();
dr["link"] = "text5";
dr["Property_name"] = "walia";
dr["Street_address"] = "sachin";
dr["walia"] = "sachin";
dt.Rows.Add(dr);
}
//PdfWriter.GetInstance(document, new FileStream(Server.MapPath(".") + "/pdf/test" + guid + ".pdf", FileMode.Create));
// string strPath = ConfigurationManager.AppSettings["Pdfpath"].ToString();
string strPath = Server.MapPath("test.pdf");
dtPDFfile = dt;
if (dtPDFfile.Rows.Count > 0)
{
CreatePdfReport(dtPDFfile, "", strPath, "sachin");
}
}
//---------------------
public void CreatePdfReport(DataTable dt, string headerText, string filepath, string filename)
{
HttpContext.Current.Response.ContentType = "Application/pdf";
Document document = new Document(PageSize.A4.Rotate(), 50, 50, 50, 50);
int numColumns = 0;
if (dt.Columns.Count > 0)
{
numColumns = dt.Columns.Count;
}
PdfPTable datatable = new PdfPTable(numColumns);
//string strPathImage = DateTime.Now.Year.ToString() + "" + DateTime.Now.Month.ToString() + "" + DateTime.Now.Day.ToString() + "" + DateTime.Now.Hour.ToString() + "" + DateTime.Now.Minute.ToString() + "" + DateTime.Now.Second.ToString() + "Image." + strExtension;
// set image path for header image
//PdfWriter.GetInstance(document, new FileStream(Environment.GetFolderPath
//(Environment.SpecialFolder.Desktop) + "\\TimeScheduler"+DateTime.Now.Year.ToString() + "" + DateTime.Now.Month.ToString() + "" + DateTime.Now.Day.ToString() + "" + DateTime.Now.Hour.ToString() + "" + DateTime.Now.Minute.ToString() + "" + DateTime.Now.Second.ToString() +".pdf", FileMode.Create));
string imagepath = Server.MapPath("logo.gif");
PdfWriter.GetInstance(document, new FileStream(filepath + "timescheduler.pdf", FileMode.Create, FileAccess.ReadWrite));
//PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create));
document.Open();
// set header image
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
image.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
//PdfPCell cell = new PdfPCell(image);
//image.HorizontalAlignment = PdfPCell.ALIGN_MIDDLE;
// set spacing betwwen table and header image
image.SpacingAfter = 20f;
//image.SpacingBefore = 10f;
image.ScalePercent(80f);
document.Add(image);
Phrase headerPhrase = new Phrase(headerText, FontFactory.GetFont("Verdana", 28));
HeaderFooter header = new HeaderFooter(headerPhrase, false);
header.Border = Rectangle.NO_BORDER;
header.Alignment = Element.ALIGN_CENTER;
document.Header = header;
document.Add(headerPhrase);
HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
footer.Border = Rectangle.NO_BORDER;
footer.Alignment = Element.ALIGN_CENTER;
document.Footer = footer;
float[] columnWidths = { 18, 40, 40, 40 };
datatable.SetWidths(columnWidths);
datatable.DefaultCell.Padding = 4;
datatable.WidthPercentage = 100; // percentage
datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
datatable.DefaultCell.BorderWidth = 1;
datatable.DefaultCell.GrayFill = 0.7f;
datatable.SpacingBefore = 50f;
foreach (DataColumn column in dt.Columns)
{
string columnName = column.ColumnName;
Phrase phrase = new Phrase(columnName, FontFactory.GetFont("Tahoma", 20, Font.BOLD));
datatable.DefaultCell.GrayFill = 0.9f;
datatable.AddCell(phrase);
}
datatable.HeaderRows = 1;
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
string columnName = column.ColumnName;
Phrase phrase = new Phrase(row[columnName].ToString(), FontFactory.GetFont("Arial", 18));
datatable.DefaultCell.GrayFill = 10f;
datatable.AddCell(phrase);
}
}
document.Add(datatable);
document.Close();
HttpContext.Current.Response.ContentType = "Application/pdf";
HttpContext.Current.Response.WriteFile(filepath + "timescheduler.pdf");
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".pdf");
HttpContext.Current.Response.TransmitFile(filepath + "timescheduler.pdf");
HttpContext.Current.Response.End();
}
and then
namespace
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.Collections;
using System.Text;
using System.Net;
using System.IO;
using System.Configuration;
//------- Function for generate pdf ---
private void newpdf()
{
Document doc = new Document(PageSize.A4);
DataTable dtPDFfile = new DataTable();
DataTable dt = new DataTable();
dt.Columns.Add("link", typeof(System.String));
dt.Columns.Add("Property_name", typeof(System.String));
dt.Columns.Add("Street_address", typeof(System.String));
dt.Columns.Add("walia", typeof(System.String));
for (Int32 i = 0; i < 30; i++)
{
DataRow dr = dt.NewRow();
dr["link"] = "text5";
dr["Property_name"] = "walia";
dr["Street_address"] = "sachin";
dr["walia"] = "sachin";
dt.Rows.Add(dr);
}
//PdfWriter.GetInstance(document, new FileStream(Server.MapPath(".") + "/pdf/test" + guid + ".pdf", FileMode.Create));
// string strPath = ConfigurationManager.AppSettings["Pdfpath"].ToString();
string strPath = Server.MapPath("test.pdf");
dtPDFfile = dt;
if (dtPDFfile.Rows.Count > 0)
{
CreatePdfReport(dtPDFfile, "", strPath, "sachin");
}
}
//---------------------
public void CreatePdfReport(DataTable dt, string headerText, string filepath, string filename)
{
HttpContext.Current.Response.ContentType = "Application/pdf";
Document document = new Document(PageSize.A4.Rotate(), 50, 50, 50, 50);
int numColumns = 0;
if (dt.Columns.Count > 0)
{
numColumns = dt.Columns.Count;
}
PdfPTable datatable = new PdfPTable(numColumns);
//string strPathImage = DateTime.Now.Year.ToString() + "" + DateTime.Now.Month.ToString() + "" + DateTime.Now.Day.ToString() + "" + DateTime.Now.Hour.ToString() + "" + DateTime.Now.Minute.ToString() + "" + DateTime.Now.Second.ToString() + "Image." + strExtension;
// set image path for header image
//PdfWriter.GetInstance(document, new FileStream(Environment.GetFolderPath
//(Environment.SpecialFolder.Desktop) + "\\TimeScheduler"+DateTime.Now.Year.ToString() + "" + DateTime.Now.Month.ToString() + "" + DateTime.Now.Day.ToString() + "" + DateTime.Now.Hour.ToString() + "" + DateTime.Now.Minute.ToString() + "" + DateTime.Now.Second.ToString() +".pdf", FileMode.Create));
string imagepath = Server.MapPath("logo.gif");
PdfWriter.GetInstance(document, new FileStream(filepath + "timescheduler.pdf", FileMode.Create, FileAccess.ReadWrite));
//PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create));
document.Open();
// set header image
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
image.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
//PdfPCell cell = new PdfPCell(image);
//image.HorizontalAlignment = PdfPCell.ALIGN_MIDDLE;
// set spacing betwwen table and header image
image.SpacingAfter = 20f;
//image.SpacingBefore = 10f;
image.ScalePercent(80f);
document.Add(image);
Phrase headerPhrase = new Phrase(headerText, FontFactory.GetFont("Verdana", 28));
HeaderFooter header = new HeaderFooter(headerPhrase, false);
header.Border = Rectangle.NO_BORDER;
header.Alignment = Element.ALIGN_CENTER;
document.Header = header;
document.Add(headerPhrase);
HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
footer.Border = Rectangle.NO_BORDER;
footer.Alignment = Element.ALIGN_CENTER;
document.Footer = footer;
float[] columnWidths = { 18, 40, 40, 40 };
datatable.SetWidths(columnWidths);
datatable.DefaultCell.Padding = 4;
datatable.WidthPercentage = 100; // percentage
datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
datatable.DefaultCell.BorderWidth = 1;
datatable.DefaultCell.GrayFill = 0.7f;
datatable.SpacingBefore = 50f;
foreach (DataColumn column in dt.Columns)
{
string columnName = column.ColumnName;
Phrase phrase = new Phrase(columnName, FontFactory.GetFont("Tahoma", 20, Font.BOLD));
datatable.DefaultCell.GrayFill = 0.9f;
datatable.AddCell(phrase);
}
datatable.HeaderRows = 1;
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
string columnName = column.ColumnName;
Phrase phrase = new Phrase(row[columnName].ToString(), FontFactory.GetFont("Arial", 18));
datatable.DefaultCell.GrayFill = 10f;
datatable.AddCell(phrase);
}
}
document.Add(datatable);
document.Close();
HttpContext.Current.Response.ContentType = "Application/pdf";
HttpContext.Current.Response.WriteFile(filepath + "timescheduler.pdf");
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".pdf");
HttpContext.Current.Response.TransmitFile(filepath + "timescheduler.pdf");
HttpContext.Current.Response.End();
}
Friday, September 16, 2011
Jquery get data by partial postback
html code : Please make a aspx page and add this code in html side..
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src ="jquery-1.4.2.min.js" ></script>
<script language="javascript" type="text/javascript">
window.onload = abc;
// $(document).ready(function ()
function abc() {
$.ajax({
type: "GET",
url: "/WebSite3/Default.aspx",
data: "mail=1&metro=2",
success: function (data) {
document.getElementById('x').innerHTML = data;
}
});
setTimeout("abc()", 1000);
};
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="x">
</span>
</div>
</form>
</body>
</html>
///---
Now add a page Default.aspx and write the below code in cs page in page load..
protected string str = "";
Random ran = new Random();
str = ran.Next(10, 2000).ToString();
//-----
Now print this function in html side
<%= str %>
Happy learing g.....
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src ="jquery-1.4.2.min.js" ></script>
<script language="javascript" type="text/javascript">
window.onload = abc;
// $(document).ready(function ()
function abc() {
$.ajax({
type: "GET",
url: "/WebSite3/Default.aspx",
data: "mail=1&metro=2",
success: function (data) {
document.getElementById('x').innerHTML = data;
}
});
setTimeout("abc()", 1000);
};
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="x">
</span>
</div>
</form>
</body>
</html>
///---
Now add a page Default.aspx and write the below code in cs page in page load..
protected string str = "";
Random ran = new Random();
str = ran.Next(10, 2000).ToString();
//-----
Now print this function in html side
<%= str %>
Happy learing g.....
Thursday, September 8, 2011
MD5 Sqr server password encrypt
CREATE FUNCTION [dbo].[fn_MD5]
(
@string AS VARCHAR(MAX),
@chars AS INT
)
RETURNS NVARCHAR(32)
AS
BEGIN
-- Declare the return variable here
DECLARE @md5 NVARCHAR(32)
SELECT @md5 = SUBSTRING(CAST(master.dbo.fn_varbintohexstr(HashBytes('MD5',@string )) AS NVARCHAR(32)),3,@chars )
-- Return the result of the function
RETURN @md5
END
select dbo.fn_MD5('hello', 32) as md5
select dbo.fn_MD5('rakeshwalia', 40) as md5
select dbo.fn_MD5('sachinrameshtendulkarserttuiklolioooooo', 40) as md5
(
@string AS VARCHAR(MAX),
@chars AS INT
)
RETURNS NVARCHAR(32)
AS
BEGIN
-- Declare the return variable here
DECLARE @md5 NVARCHAR(32)
SELECT @md5 = SUBSTRING(CAST(master.dbo.fn_varbintohexstr(HashBytes('MD5',@string )) AS NVARCHAR(32)),3,@chars )
-- Return the result of the function
RETURN @md5
END
select dbo.fn_MD5('hello', 32) as md5
select dbo.fn_MD5('rakeshwalia', 40) as md5
select dbo.fn_MD5('sachinrameshtendulkarserttuiklolioooooo', 40) as md5
SQL Script to check what was changed in database after 9PM Last night
SELECT name,
TYPE,
type_desc,
create_date,
modify_date
FROM sys.objects
WHERE TYPE IN ('U','V','PK','F','D','P')
AND modify_date >= Dateadd(HOUR,21,Cast((Cast(Getdate() - 1 AS VARCHAR(12))) AS SMALLDATETIME))
ORDER BY modify_date
--U - Table
--V - View
--PK - Primary Key
--F - Foreign Key
--D - Default Constraint
--P - Procedure
TYPE,
type_desc,
create_date,
modify_date
FROM sys.objects
WHERE TYPE IN ('U','V','PK','F','D','P')
AND modify_date >= Dateadd(HOUR,21,Cast((Cast(Getdate() - 1 AS VARCHAR(12))) AS SMALLDATETIME))
ORDER BY modify_date
--U - Table
--V - View
--PK - Primary Key
--F - Foreign Key
--D - Default Constraint
--P - Procedure
Display multiple rows values as single row value like comma separtae
SET NOCOUNT ON
DECLARE @listValues VARCHAR(8000)
DECLARE @delimeter VARCHAR(3)
SET @delimeter = ' ; '
CREATE TABLE #Table1 (FirstName varchar(10))
INSERT #Table1 VALUES ('Michiel')
INSERT #Table1 VALUES ('John')
INSERT #Table1 VALUES ('Smith')
INSERT #Table1 VALUES ('Peter')
select * from #Table1
SELECT @listValues = ISNULL(@listValues + @delimeter + CAST(FirstName AS VARCHAR(8000)),
CAST(FirstName AS VARCHAR(8000))
)
FROM #Table1
ORDER BY FirstName
DROP TABLE #Table1
SELECT list = @listValues
DECLARE @listValues VARCHAR(8000)
DECLARE @delimeter VARCHAR(3)
SET @delimeter = ' ; '
CREATE TABLE #Table1 (FirstName varchar(10))
INSERT #Table1 VALUES ('Michiel')
INSERT #Table1 VALUES ('John')
INSERT #Table1 VALUES ('Smith')
INSERT #Table1 VALUES ('Peter')
select * from #Table1
SELECT @listValues = ISNULL(@listValues + @delimeter + CAST(FirstName AS VARCHAR(8000)),
CAST(FirstName AS VARCHAR(8000))
)
FROM #Table1
ORDER BY FirstName
DROP TABLE #Table1
SELECT list = @listValues
Count all row in all table RowCount
Run this script to get the row counts of all tables.
SELECT o.name AS "Table Name", i.rowcnt AS "Row Count"
FROM sysobjects o, sysindexes i
WHERE i.id = o.id AND indid IN(0,1)
AND xtype = 'u'
AND o.name <> 'sysdiagrams'
ORDER BY i.rowcnt DESC
FROM sysobjects o, sysindexes i
WHERE i.id = o.id AND indid IN(0,1)
AND xtype = 'u'
AND o.name <> 'sysdiagrams'
ORDER BY i.rowcnt DESC
Column Headers To Row Headers in sql server
--Create Dummy test table and insert data
Declare @t table(num int, descr varchar(20), [value] decimal(9,2), date smalldatetime)
insert into @t
values(101,'Blue Skirt', '20.00', '01/01/2008')
insert into @t
values(102,'white socks', '5.000','12/03/2009')
insert into @t
values(110,'blue shirt', '10.00','01/12/2010')
insert into @t
values(200,'Red Tie', '15.99','05/03/2010')
insert into @t
values(350,'Black Belt ', '100','02/09/2011')
--Test Results
Select num, descr, [value] from @t
--Declare our Variable for the first Column Header and set date as the header Column
Declare @s varchar(8000)
Select @s=COALESCE(@s+''',''','')+cast(num as varchar(10)) +'''as'''+ convert(varchar(10),date,3) from @t
--Declare our second Row Header data
declare @v varchar(8000)
select @v=COALESCE(@v+''',''','')+ descr from @t
--Declare our Third Row Header data
declare @l varchar(8000)
select @l=COALESCE(@l+''',''','')+ cast([value] as varchar(10)) from @t
--Execute all variables as well as inserting our Coulumn header
Exec('Select ''ID'' as ''Name'','''+ @s + ''' union all select ''Item'','''+ @v + ''' union all select ''Price'',''' +@l + '''' )
Declare @t table(num int, descr varchar(20), [value] decimal(9,2), date smalldatetime)
insert into @t
values(101,'Blue Skirt', '20.00', '01/01/2008')
insert into @t
values(102,'white socks', '5.000','12/03/2009')
insert into @t
values(110,'blue shirt', '10.00','01/12/2010')
insert into @t
values(200,'Red Tie', '15.99','05/03/2010')
insert into @t
values(350,'Black Belt ', '100','02/09/2011')
--Test Results
Select num, descr, [value] from @t
--Declare our Variable for the first Column Header and set date as the header Column
Declare @s varchar(8000)
Select @s=COALESCE(@s+''',''','')+cast(num as varchar(10)) +'''as'''+ convert(varchar(10),date,3) from @t
--Declare our second Row Header data
declare @v varchar(8000)
select @v=COALESCE(@v+''',''','')+ descr from @t
--Declare our Third Row Header data
declare @l varchar(8000)
select @l=COALESCE(@l+''',''','')+ cast([value] as varchar(10)) from @t
--Execute all variables as well as inserting our Coulumn header
Exec('Select ''ID'' as ''Name'','''+ @s + ''' union all select ''Item'','''+ @v + ''' union all select ''Price'',''' +@l + '''' )
Fo Find exact age in sql server
/*----------------------------------------------------------------------------------------------------------------------------
Author :- ANAND BABU UCHAGAWKAR
Purpose :- To find the datediff/age in text format (eg. 1 year(s), 10 month(s), 10 day(s)).
DATE :- 30-Aug-2011
DATABASE :- SQL
----------------------------------------------------------------------------------------------------------------------------*/
IF (Select COUNT(*) From Sysobjects Where [name] like 'FN_GETDATEDIFFTEXT') > 0
BEGIN
DROP FUNCTION FN_GETDATEDIFFTEXT
END
GO
CREATE FUNCTION FN_GETDATEDIFFTEXT(@FromDate DateTime, @ToDate DateTime)
RETURNS NVARCHAR(50)
AS
BEGIN
Declare @daysDiff Int
Declare @monthDiff Int
Declare @yearDiff Int
--Select @daysDiff = DATEDIFF(DAY, @FromDate, @ToDate)
Set @monthDiff = ABS(DATEDIFF(MONTH, @FromDate, @ToDate)%12)
Set @yearDiff = ABS(DATEDIFF(YYYY, @FromDate, @ToDate))
-- If the From date month is greater than the month of the To date and the year difference is greater than zero
-- then the year should the deducted by one
IF DATEPART(MONTH,@FromDate) > DATEPART(MONTH,@ToDate) AND @yearDiff > 0
BEGIN
Set @yearDiff = @yearDiff - 1
END
IF DATEPART(DAY,@FromDate) > DATEPART(DAY, @ToDate)
Begin
--Get last date of the month of the FromDate
Declare @lastDateOfMonth DateTime = DATEADD(MONTH, 1, @FromDate)
Set @lastDateOfMonth = '01-' + DATENAME(MONTH,@lastDateOfMonth) + '-'+DATENAME(YEAR,@lastDateOfMonth)
Set @lastDateOfMonth = DATEADD(DAY, -1, @lastDateOfMonth)
Set @daysDiff = DATEDIFF(DAY, @FromDate, @lastDateOfMonth)
Set @daysDiff = @daysDiff + DATEPART(DAY, @ToDate)
Set @monthDiff = @monthDiff - 1
End
ELSE
BEGIN
Set @daysDiff = DATEPART(DAY, @ToDate) - DATEPART(DAY, @FromDate)
END
-- Select @yearDiff Yr, @monthDiff Mn, @daysDiff Dy
RETURN
CAST(@yearDiff as nvarchar) + ' year(s), ' +
CAST(@monthDiff as nvarchar) + ' month(s), ' +
CAST(@daysDiff as nvarchar) + ' day(s)'
END
GO
-- Select DBO.FN_GETDATEDIFFTEXT('30-Dec-2010', '31-Jan-2011')
-- Select DBO.FN_GETDATEDIFFTEXT('01-Jan-1990', Getdate())
Select DBO.FN_GETDATEDIFFTEXT('24-feb-1983', Getdate())
Tuesday, September 6, 2011
Silverlight pop up window [4.0]
Please add this code on click event :
private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Popup p;
// Create a popup.
p = new Popup();
// Set the Child property of Popup to an instance of MyControl.
p.Child = new Views.SilverlightControl1();
// Set where the popup will show up on the screen.
p.VerticalOffset = 600;
p.HorizontalOffset = 600;
// Open the popup.
p.IsOpen = true;
//MessageBox.Show(dataGrid1.CurrentColumn.Header.ToString() + ": " +
// ((TextBlock)dataGrid1.CurrentColumn.GetCellContent(dataGrid1.SelectedItem)).Text);
}
//------------------------------
private void CloseBtn_Click(object sender, RoutedEventArgs e)
{
this.Visibility = Visibility.Collapsed;
}
private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Popup p;
// Create a popup.
p = new Popup();
// Set the Child property of Popup to an instance of MyControl.
p.Child = new Views.SilverlightControl1();
// Set where the popup will show up on the screen.
p.VerticalOffset = 600;
p.HorizontalOffset = 600;
// Open the popup.
p.IsOpen = true;
//MessageBox.Show(dataGrid1.CurrentColumn.Header.ToString() + ": " +
// ((TextBlock)dataGrid1.CurrentColumn.GetCellContent(dataGrid1.SelectedItem)).Text);
}
//------------------------------
private void CloseBtn_Click(object sender, RoutedEventArgs e)
{
this.Visibility = Visibility.Collapsed;
}
Tuesday, August 30, 2011
Get silverlight datagrid selected index value
private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show(dataGrid1.CurrentColumn.Header.ToString() + ": " +
((TextBlock)dataGrid1.CurrentColumn.GetCellContent(dataGrid1.SelectedItem)).Text);
}
Thursday, July 14, 2011
new
http://hosting.gmodules.com/ig/gadgets/file/112581010116074801021/fish.swf?%22%20width=%22100%%22%20height=%22100%
Tuesday, July 5, 2011
Create PDF document using iTextSharp in ASP.Net 4.0 and MemoryMappedFile
Create PDF document using iTextSharp in ASP.Net 4.0 and MemoryMappedFile
In this article I am going to demonstrate how ASP.Net developers can programmatically create PDF documents using iTextSharp. iTextSharp is a software component, that allows developers to programmatically create or manipulate PDF documents. Also this article discusses the process of creating in-memory file, read/write data from/to the in-memory file utilizing the new feature MemoryMappedFile.I have a database of users, where I need to send a notice to all my users as a PDF document. The sending mail part of it is not covered in this article. The PDF document will contain the company letter head, to make it more official.
I have a list of users stored in a database table named “tblusers”. For each user I need to send customized message addressed to them personally. The database structure for the users is give below.
| id | Title | Full Name |
| 1 | Mr. | Sreeju Nair K. G. |
| 2 | Dr. | Alberto Mathews |
| 3 | Prof. | Venketachalam |
Dear <Title> <FullName>,Also I have an image, bg.jpg that contains the background for the document generated.
The message for the user.
Regards,
Administrator
I have created .Net 4.0 empty web application project named “iTextSharpSample”. First thing I need to do is to download the iTextSharp dll from the source forge. You can find the url for the download here. http://sourceforge.net/projects/itextsharp/files/
I have extracted the Zip file and added the itextsharp.dll as a reference to my project. Also I have added a web form named default.aspx to my project. After doing all this, the solution explorer have the following view.
In the default.aspx page, I inserted one grid view and associated it with a SQL Data source control that bind data from tblusers. I have added a button column in the grid view with text “generate pdf”. The output of the page in the browser is as follows.
Now I am going to create a pdf document when the user clicking on the Generate PDF button. As I mentioned before, I am going to work with the file in memory, I am not going to create a file in the disk. I added an event handler for button by specifying onrowcommand event handler. My gridview source looks like
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"In the code behind, I wrote the corresponding event handler.
DataSourceID="SqlDataSource1" Width="481px"
CellPadding="4" ForeColor="#333333" GridLines="None"
onrowcommand="Generate_PDF" >
…………………………………………………………………………..
…………………………………………………………………………..
</asp:GridView>
protected void Generate_PDF(object sender, GridViewCommandEventArgs e)The Generate_PDF method is straight forward, It get the title, fullname and message to some variables, then create the pdf using these variables.
{
// The button click event handler code.}
// I am going to explain the code for this section in the remaining part of the article
The code for getting data from the grid view is as follows
// get the row index stored in the CommandArgument propertysince I don’t want to save the file in the disk, I am going the new feature introduced in .Net framework 4, called Memory-Mapped Files. Using Memory-Mapped mapped file, you can created non-persisted memory mapped files, that are not associated with a file in a disk. So I am going to create a temporary file in memory, add the pdf content to it, then write it to the output stream.
int index = Convert.ToInt32(e.CommandArgument);
// get the GridViewRow where the command is raised
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string title = selectedRow.Cells[1].Text;
string fullname = selectedRow.Cells[2].Text;
string msg = @"There are some changes in the company policy, due to this matter you need to submit your latest address to us. Please update your contact details personnal details by visiting the member area of the website. ................................... ";
To read more about MemoryMappedFile, read this msdn article
http://msdn.microsoft.com/en-us/library/dd997372.aspx
The below portion of the code using MemoryMappedFile object to create a test pdf document in memory and perform read/write operation on file. The CreateViewStream() object will give you a stream that can be used to read or write data to/from file. The code is very straight forward and I included comment so that you can understand the code.
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test1.pdf", 1000000))
{
// Create a new pdf document object using the constructor. The parameters passed are document size, left margin, right margin, top margin and bottom margin.
Press ctrl + f5 to run the application. First I got the user list. Click on the generate pdf icon. The created looks as follows.iTextSharp.text.Document d = new iTextSharp.text.Document(PageSize.A4, 72,72,172,72);//get an instance of the memory mapped file to stream object so that user can write to thisusing (MemoryMappedViewStream stream = mmf.CreateViewStream()){// associate the document to the stream.PdfWriter.GetInstance(d, stream);//add an image as bgiTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(Server.MapPath("Image/bg.png"));jpg.Alignment = iTextSharp.text.Image.UNDERLYING;jpg.SetAbsolutePosition(0, 0);
//this is the size of my background letter head image. the size is in points. this will fit to A4 size document.
jpg.ScaleToFit(595, 842);
d.Open();
d.Add(jpg);
d.Add(new Paragraph(String.Format("Dear {0} {1},", title, fullname)));
d.Add(new Paragraph("\n"));
d.Add(new Paragraph(msg));
d.Add(new Paragraph("\n"));
d.Add(new Paragraph(String.Format("Administrator")));
d.Close();}//read the data from the file and send it to the response streambyte[] b;using (MemoryMappedViewStream stream = mmf.CreateViewStream()){BinaryReader rdr = new BinaryReader(stream);b = new byte[mmf.CreateViewStream().Length];rdr.Read(b, 0, (int)mmf.CreateViewStream().Length);}Response.Clear();Response.ContentType = "Application/pdf";Response.BinaryWrite(b);Response.End();}
Summary:
ASP.NET Twitter Link Tracker for Friend Posts via Twitter and Ottter APIs
Download the code :
http://eggheadcafe.com/FileUpload/1145921998_OtterApiFriendLinks.zip
The result should look something like this:

http://eggheadcafe.com/FileUpload/1145921998_OtterApiFriendLinks.zip
The result should look something like this:
Wednesday, April 20, 2011
Accessing the methods of a MasterPage from inside the Web Form
write this code inside child page of masterpage to access a control.
Label lblmsg;
lblmsg = (Label)Master.FindControl("lblTitle");
lblmsg.Text = "I love my india";
//----------------------------------
((EmpMasterPage)this.Master).SetMessage("I love my India");
here EmpMasterPage is a name of MasterPage and SetMessage is a method of that MasterPage.
here EmpMasterPage is a name of MasterPage and SetMessage is a method of that MasterPage.
Bind check box in datalist and show the selected checked
<asp:DataList ID="da" runat="server" ShowHeader="False" ShowFooter="False"
CellPadding="0" RepeatColumns="1" RepeatDirection="Vertical" style="overflow:scroll !important;">
<ItemStyle Width="200" HorizontalAlign="Left"></ItemStyle>
<ItemTemplate>
<input type="checkbox" class="radio_botton" value='<%# DataBinder.Eval(Container.DataItem, "uid")%>'
name='chk' <%# search != null && search.chk.IndexOf("," + DataBinder.Eval(Container.DataItem, "uid").ToString() + ",") > -1 ? "checked" : ""%>><%# DataBinder.Eval(Container.DataItem, "Amen_Name")%>
</ItemTemplate>
</asp:DataList>
CellPadding="0" RepeatColumns="1" RepeatDirection="Vertical" style="overflow:scroll !important;">
<ItemStyle Width="200" HorizontalAlign="Left"></ItemStyle>
<ItemTemplate>
<input type="checkbox" class="radio_botton" value='<%# DataBinder.Eval(Container.DataItem, "uid")%>'
name='chk' <%# search != null && search.chk.IndexOf("," + DataBinder.Eval(Container.DataItem, "uid").ToString() + ",") > -1 ? "checked" : ""%>><%# DataBinder.Eval(Container.DataItem, "Amen_Name")%>
</ItemTemplate>
</asp:DataList>
Wednesday, April 13, 2011
SQL SERVER – Add New Column With Default Value
SQL Server is a very interesting system, but the people who work in SQL Server are even more remarkable. The amount of communication, the thought process, the brainstorming that they do are always phenomenal. Today I will share a quick conversation I have observed in one of the organizations that I recently visited.
While we were heading to the conference room, we passed by some developers and I noticed the following script on the screen of one of the developers.
CREATE TABLE TestTable
(FirstCol INT NOT NULL)
GO
------------------------------
-- Option 1
------------------------------
-- Adding New Column
ALTER TABLE TestTable
ADD SecondCol INT
GO
-- Updating it with Default
UPDATE TestTable
SET SecondCol = 0
GO
-- Alter
ALTER TABLE TestTable
ALTER COLUMN SecondCol INT NOT NULL
GO
Curious, I asked why he wrote such a long script. He replied with another question, asking whether there is any existing short method that he can use to add a column which is not null and can be populated with some specific values.
Of course! The method exists and here is the quick script. When he learned it he said, “Well, I searched at your blog but it was not there.”
------------------------------
-- Option 2
------------------------------
-- Adding Value with Default Value
ALTER TABLE TestTable
ADD ThirdCol INT NOT NULL DEFAULT(0)
GOWell, now it’s in my blog.
SQL Server Reporting Services (SSRS): Part 1- Basics of creating a report
Introduction
SQL Server Reporting services are very good features provided in SQL to build a report of user choice and deploy it to make use of it anywhere as per the requirement. In this article we are going to see on how to create a simple report then build and execute the report. Reports can be exported to multiple formats including delimited text, XML format, PDF format and Microsoft Excel as well.
Let's jump into the process and see the step by step process of how to create and execute an SSRS report.
Steps:
Go to SQL Server Business Intelligence Development Studio and create a new project as shown below:
Now a wizard will / may open based on the existing option selected; if it opens then just skip that window by clicking Next. It will open a new window which shows the basic configuration as shown in the screen below:
Next window will show an option to build a query based on which the result set will be displayed as a report. We can write our own query to fetch the output as shown in the screen below.
Clicking on Next; a window will open with the option to select how the result should display as shown in the screen below:
Clicking on Next will open the window below; if you can see the option here to group the data and show as per our requirement.
Clicking on the Next button will open a window which gives options to design the report based on the templates available as shown in the screen below:
Now when clicking on the button an interesting thing appears, which is nothing but where to deploy the report. We can give as per our requirement
Clicking on Next will open a window as shown in the screen below. Here we can give our customized report name:
Clicking on Finish will open a window as shown in the screen below, which shows the structure of the report as shown below:
Now press F5 to build and execute the process. It will show the result as shown in the figure below:
Conclusion
So in this article we have seen how to create, build and execute a basic report using SQL reporting services.
Test Emails in ASP.NET without a Mail Server
This summary is not available. Please
click here to view the post.
Monday, April 4, 2011
implement advance search
ALTER PROCEDURE [dbo].[advance_search]
@zip_code varchar(10) = null,
@bedrooms float = null,
@bathrooms float = null,
@price_min money = null,
@price_max money = null,
@built int = null,
@sq_ft int = null,
@aptType_id int = null,
@minLong real = null,
@maxLong real = null,
@minLat real = null,
@maxLat real = null,
@amenities varchar(100) = null,
@amenityCnt int = null,
@longitudes varchar(8000) = null,
@latitudes varchar(8000) = null,
@filter varchar(1000) = null,
@pageNum int = 1,
@pageSize smallint = 50,
@wd bit = 1
, @High_Altitude varchar(50)= 'false
CommissionAmount, @Search_Para
, @Commission_Amount varchar(50)= null
, @Search_Para varchar(50) = null
AS
begin
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
Begin Transaction
DECLARE @firstRecord int, @lastRecord int
SET @firstRecord = (@pageNum - 1) * @pageSize + 1
SET @lastRecord = (@pageNum * @pageSize)
declare @exec varchar(8000)
set @exec = 'SELECT DISTINCT complexes_active.UID,CommissionAmount,complexes_active.Property_Name,
complexes_active.Street_Address_1,complexes_active.City,complexes_active.metro_area,Longitude,Latitude,
Survey_Date,(SELECT COUNT(*) FROM apartment_graphics with (updlock)
WHERE apartment_id=complexes_active.uid AND type = ''.JPG'') AS gr, promoted,property_status,
State, Zip_Code, Telephone_Number'
If @amenities is not null
set @exec = @exec + ',(select count(*) from ACAmenities with (updlock) where ac_uid=complexes_active.UID and Amenity_id in (' + @amenities + ')) as foundAmens'
set @exec = @exec + ' into #tPaging FROM complexes_active with (updlock) INNER JOIN apartment_units ON apartment_units.AC_UID=complexes_active.UID'
If (@Search_Para is not null)
set @exec = @exec + ' Inner Join submarkets On submarkets.smrkt_Id = complexes_active.submarketid '
set @exec = @exec + ' WHERE 1=1 '
If @ManagementID is not null
set @exec = @exec + ' AND Management_UID=''' + cast(@ManagementID as varchar(6)) + ''''
else
If @city is not null
set @exec = @exec + ' AND City=''' + @city + ''''
If @Metro_Area is not null
set @exec = @exec + ' AND Metro_Area=''' + @Metro_Area + ''''
If @city_region is not null
set @exec = @exec + ' AND City_Region in (' + @city_region + ')'
If @zip_code is not null
set @exec = @exec + ' AND zip_code LIKE ''' + @zip_code + '%'''
If @Property_Name is not null
Begin
set @exec = @exec + ' AND ' + dbo.f_PropertyNames(@Property_Name)
--set @exec= @exec +' or '+ dbo.f_FKANames(@Property_Name)
End
If @Street_Address is not null
set @exec = @exec + ' AND Street_Address_1 like ''%' + @Street_Address + '%'''
If @built is not null
set @exec = @exec + ' AND Year_Built>=''' + CAST(@built as varchar(4)) + ''''
If @minLong is not null and @maxLong is not null and @minLat is not null and @maxLat is not null
set @exec = @exec + ' AND Longitude between ' + CAST(@minLong as varchar(12)) + ' and ' + CAST(@maxLong as varchar(12)) + ' and Latitude between ' + CAST(@minLat as varchar(12)) + ' and ' + CAST(@maxLat as varchar(12))
If @price_max is not null or @price_min is not null or @bedrooms is not null or @bathrooms is not null or @sq_ft is not null or @aptType_id is not null or @wd = 1
set @exec = @exec + ' AND PFP_DELETED = 0'
If @aptType_id is not null
set @exec = @exec + ' AND PFP_CC_ID_UNITTYPE=' + CAST(@aptType_id as varchar(10))
If @price_min is not null
set @exec = @exec + ' AND PFP_MarketRentMin>' + CAST(@price_min as varchar(10))
If @price_max is not null
set @exec = @exec + ' AND PFP_MarketRentMin<' + CAST(@price_max as varchar(10))
If @bedrooms is not null
set @exec = @exec + ' AND PFP_NumBed=' + CAST(@bedrooms as varchar(3))
If @bathrooms is not null
set @exec = @exec + ' AND PFP_NumBath=' + CAST(@bathrooms as varchar(3))
If @sq_ft is not null
set @exec = @exec + ' and PFP_SqFt>=' + cast(@sq_ft as varchar(5))
if (@Commission_Amount is not null)
set @exec = @exec + ' and CommissionAmount >= '+ @Commission_Amount -- added by Tarveen to make filter for Commission_Amount
If (lower(@High_Altitude) = 'true') -- added by Tarveen to make filter for High_Rise
set @exec = @exec + ' and High_Altitude = 1'
If (@Search_Para is not null) -- added by Tarveen to make filter for Galleria and Midtown
set @exec = @exec + ' and submarkets.smrkt_name = '''+ @Search_Para + ''''
If @amenities is not null
set @exec = @exec + ' AND 1<=(select count(*) from ACAmenities with(updlock)
where ac_uid=complexes_active.UID and Amenity_id in (' + @amenities + '))'
If @filter is not null
set @exec = @exec + @filter
If @amenities is not null
set @exec = @exec + ' order by foundAmens desc, gr desc, CommissionAmount desc, Property_Name'
else
set @exec = @exec + ' order by gr desc, CommissionAmount desc, Property_Name'
If @amenityCnt is not null and @amenityCnt>0
begin
SET @exec = @exec + '; SELECT COUNT(*) FROM #tPaging with(updlock) where foundAmens=' + CAST(@amenityCnt as varchar(3))
SET @exec = @exec + '; SELECT * FROM #tPaging with(updlock) where foundAmens=' + CAST(@amenityCnt as varchar(3))
end
else
begin
SET @exec = @exec + '; SELECT COUNT(*) FROM #tPaging with(updlock)'
SET @exec = @exec + '; SELECT * FROM #tPaging with(updlock)'
end
print @exec
exec (@exec)
commit transaction
if(@@error > 0)
rollback
end
Subscribe to:
Comments (Atom)