Wednesday, November 26, 2008

Save And Retrive Any format file to database

//--Data base table required sql server-2005
column 1.Id(Pk)
2.FileName(nvarchar(max))
3.FileData(varbinary(max))


private void SaveFile()
{
try
{
if (txtFile .Text != "")
{
FileStream fs;
fs = new FileStream(txtFile.Text, FileMode.OpenOrCreate, FileAccess.ReadWrite);
BinaryReader br;
br=new BinaryReader(fs);
////a byte array to read the image
byte[] picbyte = br.ReadBytes ((int)fs.Length);
//byte[] picbyte = new byte[fs.Length];
// br.Close();
fs.Close();
//open the database using odp.net and insert the data
string connstr = "Data Source=IT-DHAVAL\\SQLEXPRESS;Initial Catalog=treeview;User ID=sa;PWD=sa123";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string query;
SqlParameter Fileparameter = new SqlParameter();
query = "insert into files(FileName,FileData) values('" +txtFile.Text + "',"+"@pic)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("pic",SqlDbType.VarBinary,picbyte.Length).Value=picbyte;
cmd.ExecuteNonQuery();
MessageBox.Show("FileSave");
cmd.Dispose();
conn.Close();
conn.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnRetrive_Click(object sender, EventArgs e)
{
string connstr = "Data Source=IT-DHAVAL\\SQLEXPRESS;Initial Catalog=treeview;User ID=sa;PWD=sa123";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SqlDataAdapter empadap1 = new SqlDataAdapter();
empadap1.SelectCommand = new SqlCommand("SELECT * FROM files", conn);
DataSet dset = new DataSet("dset");
empadap1.Fill(dset);
DataTable dtable;
dtable = dset.Tables[0];
DataTable dataTable = dset.Tables[0];
foreach (DataRow dataRow in dataTable.Rows)
{
FileStream FS1 = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\" + (string)dataRow[1], FileMode.Create);
byte[] blob = (byte[])dataRow[2];
FS1.Write(blob, 0, blob.Length);
FS1.Close();
FS1 = null;
}
}

Thursday, October 23, 2008

Tab based MDI from

When the MDI Child Form is activated; if child form has a tab page, activate the corresponding tab page else create a tab page for child form and select tab page.

private void Form1_MdiChildActivate(object sender,
EventArgs e)
{
if (this.ActiveMdiChild == null)
tabForms.Visible = false;
// If no any child form, hide tabControl

else
{
this.ActiveMdiChild.WindowState =
FormWindowState.Maximized;
// Child form always maximized


// If child form is new and no has tabPage,

// create new tabPage

if (this.ActiveMdiChild.Tag == null)
{
// Add a tabPage to tabControl with child

// form caption

TabPage tp = new TabPage(this.ActiveMdiChild
.Text);
tp.Tag = this.ActiveMdiChild;
tp.Parent = tabForms;
tabForms.SelectedTab = tp;

this.ActiveMdiChild.Tag = tp;
this.ActiveMdiChild.FormClosed +=
new FormClosedEventHandler(
ActiveMdiChild_FormClosed);
}

if (!tabForms.Visible) tabForms.Visible = true;

}
}

When the MDI Child Form is closing, destroy the corresponding tab page. Add the following code to main form.

private void ActiveMdiChild_FormClosed(object sender,
FormClosedEventArgs e)
{
((sender as Form).Tag as TabPage).Dispose();
}

When a tab page selected, activate its child form

private void tabForms_SelectedIndexChanged(object sender,
EventArgs e)
{
if ((tabForms.SelectedTab != null) &&
(tabForms.SelectedTab.Tag != null))
(tabForms.SelectedTab.Tag as Form).Select();
}

Tuesday, September 2, 2008

Ajax Class

//var //xmlHttp = //createXmlHttpRequestObject();
// function //createXmlHttpRequestObject()
// {
// try
// {
// // try to create XMLHttpRequest object
// //xmlHttp = new //XMLHttpRequest();
// }
//catch(e)
//{
// var //XmlHttpVersions = new //Array("MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0", //"MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP");
// for (var i=0; i // {
// try
// {
// // xmlHttp = new //ActiveXObject(//XmlHttpVersions[i]);
// }
//catch (e)
// {}
//}
//}
//if (!//xmlHttp)
// alert("Error creating the //XMLHttpRequest object.");
//else
//return //xmlHttp;
//}
//Pass Your Data in below function
//Url is Url of your Ajax Pages
//TimerFunction function name for if serverbusy then which function called e.g:test()
//TimerDelay is delay calll timer
//Wait Function in server busy mode which image call or text display
//here pass only function name like test not test().and in this funtion put status argument value off and value on
//RequestFor= type charcter which u want which user in AjaxResponse() funtion as per your value call ServerResponse Funtion that will return xmlRootnode
//Now put One Funtion name as exactly=AjaxResponse(RequestFor)
//function AjaxRequest(Url,TimerFunction,TimeDelay,WaitFunction,RequestFor)
//{
// if(//xmlHttp)
//{
// try
//{
// if((//xmlHttp.readyState==0)||(//xmlHttp.readyState==4))
// {
// try
// {
// //xmlHttp.open("GET", Url, true);
//}
// catch(e)
// {
// alert("File not found"+e);
// }
// // state Change Function
// //xmlHttp.onreadystatechange=
// function AjaxStateChange()
// {
// if(//xmlHttp.readyState==1 ||//xmlHttp.readyState==3 || //xmlHttp.readyState==2)
// {
// //If server busy then wait message comes in picture with //body disabled
// setTimeout(""+WaitFunction+"('on')"+"",0);
// }
// else if (//xmlHttp.readyState == 4)
// {
// setTimeout(""+WaitFunction+"('off')"+"",0);
//Now Server not busy and ready with output
// if (//xmlHttp.status == 200)
// {
// try
// {
//Server Response Funtion
// //AjaxResponse(RequestFor);
// }
// catch(e)
// {
// alert("Error reading the response: " + //e.toString());
// }
// }
// else
// {
// alert("There was a problem retrieving the data:\n" //+//xmlHttp.statusText);
// }
// }
// }
// //----------------
// //xmlHttp.send(null);
// }
// else
// {
// setTimeout(""+TimerFunction+"",TimeDelay);
// }
// }
// catch (e)
// {
// alert("Can't connect to server:\n" + e.toString());
// }
//}
//return false;
// }
// function AjaxResponse(RequestFor)
//{
// var //xmlResponse = //xmlHttp.responseXML;

// if (//!xmlResponse || //!xmlResponse.documentElement)
// throw("Invalid XML structure:\n" + //xmlHttp.responseText);
//var rootNodeName = ///xmlResponse.documentElement.nodeName;
//if (rootNodeName == "parsererror")
// throw("Invalid XML structure");
// //xmlRoot = xmlResponse.documentElement;
//GetResponse(//xmlRoot,RequestFor);
//}
//function GetResponse(Root,RequestFor)
//{
// if(RequestFor=='ValueToMatch')
// {
// ServerResponseFunction1(Root);
//}
//else if(RequestFor=='ValueToMatch')
//{
// ServerResponseFunction2(Root);
//}

//}

Thursday, August 14, 2008

PHP_IMAGE_FROM_DATABASE

To Upload DataBase:
$filename=$_FILES['imgfile']['name'];
$img="C:\\PHP\\uploadtemp\\".$_FILES['imgfile']['name'];

#
$fh = fopen($_FILES['imgfile']['tmp_name'], "rb");
#
$imgdata = addslashes(fread($fh, filesize($_FILES['imgfile']['tmp_name'])));
#
fclose($fh);
$imgdata store to database as variable
Retrive Image Form Database:
$UserId=$_REQUEST['get'];
//$UserId=1;
$dbconn = mysql_connect('localhost','root','admin') or exit("SERVER Unavailable");
$db=mysql_select_db('test',$dbconn) or exit("DB Unavailable");
$query = "SELECT Image FROM UserLogin where UserId=$UserId";
$result = mysql_query($query, $dbconn) or die('Check Sql Statement');
$result_data = mysql_fetch_array($result, MYSQL_ASSOC);
$img=$result_data['Image'];


if (!empty($img))
{
header("Content-Type: image/jpeg");
$img=$result_data['Image'];
echo $img;
}
else
{
$imgfile="../Image/NotFound.jpg";
$img=imagecreatefromjpeg($imgfile);
header("Content-Type: image/jpeg");
imagejpeg($img);
}
exit();
?>

Saturday, August 2, 2008

Javascript for Work WIth Ajax

// JavaScript Document
//var xmlHttp = //createXmlHttpRequestObject();

//IF Page Submit/Postback
TimerId=0;
TimerId=setTimeout('GetPastDtl(document.getElementById("CompList").value)',1000);
function createXmlHttpRequestObject()
{
try
{
// try to create XMLHttpRequest object
//xmlHttp = new //XMLHttpRequest();
}
catch(e)
{
var //XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP");
//for (var i=0; i";
document.getElementById('DeptList').options.add(k);
for (var i=0; i
document.getElementById('EmpList').options.add(l);
for (var m=0; m0)
{
i=document.getElementById('EditedRowNo').value;
GetEditMode('divEd'+i,'divRd'+i,'divNameEd'+i,'divNameRd'+i,'divMailEd'+i,'divMailRd'+i,ENameDtlArray.length);
}

}
function GetEmpDetail()
{
CompId=document.getElementById('CompList').value;
DeptId=document.getElementById('DeptList').value;
EmpId=document.getElementById('EmpList').value;
PageSize=document.getElementById('hdnPageSize').value;
Offset=document.getElementById('hdnoffset').value;
CurrnentPg=document.getElementById('hdnCurrPg').value;
TotalPg=document.getElementById('hdnTotalRow').value;
if (xmlHttp)
{
try
{
if((xmlHttp.readyState==0)||(xmlHttp.readyState==4))
{
var params = "CompId=" + CompId+"&DeptId="+DeptId+"&EmpId="+EmpId+"&PageSize="+PageSize+"&Offset="+Offset;
//xmlHttp.open("GET", "Xml/EmpToDetail.php?" + params, true);
//xmlHttp.onreadystatechange = EmpDtlRequestStateChange;
//xmlHttp.send(null);
}
else
{
setTimeout('GetEmpDetail()',1000);
}
}
catch (e)
{
alert("Can't connect to server:\n" + e.toString());
}
}
}
function CreateTd(id,style,className,innerHTML)
{
Td=document.createElement("td","");
Td.setAttribute("id",id);
Td.setAttribute("style",style);
Td.className=className;
Td.innerHTML=innerHTML;
return Td;
}
function CreateTextBox(AttributeArray,ValueArray,Value)
{
inputName=document.createElement("input","");
for(i=0;i<=AttributeArray.length-1;i++) { inputName.setAttribute(AttributeArray[i],ValueArray[i]); } inputName.value=Value; return inputName; } function GridTable() { document.getElementById("EmpDetail").innerHTML=""; div=document.getElementById("EmpDetail"); //Generate Table Table=document.createElement("table",""); Table.setAttribute("style","width:100%"); Table.setAttribute("cellpadding","0"); Table.setAttribute("cellspacing","0"); Table.setAttribute("border","1"); //Generate Row Tr=document.createElement("tr",""); //Generate Column1 Td1=CreateTd('','width:40%','TdDataHeading','Name'); Tr.appendChild(Td1); //Generate Column2 Td2=CreateTd('','width:40%','TdDataHeading','Email'); Tr.appendChild(Td2); //Generate Coloumn3 Td3=CreateTd('','width:20%','TdDataHeading','Manage'); Tr.appendChild(Td3); Table.appendChild(Tr); ENameDtlArray = xmlRoot.getElementsByTagName("Ename"); EmailDtlArray = xmlRoot.getElementsByTagName("Email"); EContactIdArray=xmlRoot.getElementsByTagName("EContactId"); for (var i=0; i

Thursday, May 29, 2008

Gridview- Pagging

--------------Step-1----------
Add Folowing code in .aspx page in asp:gridview paging templete
------------------------------


EnableViewState="false" Text="Previous" CommandName="page" CommandArgument="prev">

 | 
EnableViewState="false" Text="Next" CommandName="page" CommandArgument="next">

  
Text=' SSLib.GetPosition(gvOrderList)'>



-----------------------------------------------
---------------------step-2-------------------
in back-side-aspx.vb page add following
----------------------------------------------
Protected Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
Dim Paging As New GridViewPaging
Paging.GridViewPaging(gvClientList)
End Sub
-------------------------------------------------
---------------------step-3------------------
-------------------------------------------
add following 2-class in project------------
-------------------------------------------
Class1=
-------
Public Class GridViewPaging
Function GridViewPaging(ByVal GridViewId As GridView) As Boolean
Dim pagetoprow As GridViewRow = GridViewId.TopPagerRow
Dim pagerbotomrow As GridViewRow = GridViewId.BottomPagerRow
If Not (IsNothing(pagerbotomrow)) Then
If (GridViewId.PageIndex) = 0 Then
CType(GridViewId.BottomPagerRow.FindControl("lbPrevious"), LinkButton).Enabled = False
CType(GridViewId.BottomPagerRow.FindControl("lbPrevious"), LinkButton).CssClass = "DisableLink"
End If
If (GridViewId.PageIndex + 1) = GridViewId.PageCount Then
CType(GridViewId.BottomPagerRow.FindControl("lbNext"), LinkButton).Enabled = False
CType(GridViewId.BottomPagerRow.FindControl("lbNext"), LinkButton).CssClass = "DisableLink"
End If
End If
If Not (IsNothing(pagetoprow)) Then
If (GridViewId.PageIndex) = 0 Then
CType(GridViewId.TopPagerRow.FindControl("lbPrevious"), LinkButton).Enabled = False
CType(GridViewId.TopPagerRow.FindControl("lbPrevious"), LinkButton).CssClass = "DisableLink"
End If
If (GridViewId.PageIndex + 1) = GridViewId.PageCount Then
CType(GridViewId.TopPagerRow.FindControl("lbNext"), LinkButton).Enabled = False
CType(GridViewId.TopPagerRow.FindControl("lbNext"), LinkButton).CssClass = "DisableLink"
End If
End If
End Function
---------------------------------------
------class2-----------
--------------------------------------
Public Shared Function GetPosition(ByVal gv As GridView) As String
Return "( " & (gv.PageIndex + 1).ToString & " of " & gv.PageCount & " )"
End Function

Public Shared Function GetPosition(ByVal fv As FormView) As String
Return "( " & (fv.PageIndex + 1).ToString & " of " & fv.PageCount & " )"
End Function

Public Shared Function GetPageIndex(ByVal idx As Integer) As Integer
Return idx + (CInt(HttpContext.Current.Request("Pg")) * 12)
End Function

Javascript-Auto call function

onLoad=window.setTimeout("StartText(25)",100);
var y
var timerID = 0;
function StartText(x)
{
document.getElementById ('AdOrCon').style .fontSize =x+"px";
if (x==40)
{y=1;}
else{
y=x+1;}
clearTimeout(timerID);
timerID=0;
timerID=setTimeout("StartText(y)",100);
}
function showTab(x)
{
document.getElementById('Div1').style.display="none";
document.getElementById('Div2').style.display="none";
document.getElementById('Div3').style.display="none";
document.getElementById('Div4').style.display="none";
document.getElementById('Div5').style.display="none";
document.getElementById('Div'+x).style.display="";
if (x==5)
{ y=1 ;}
else
{ y=x+1; }
clearTimeout(timerID);
timerID=0;
timerID = setTimeout("showTab(y)", 10000);

}

Javascript-window open

window.open(('ZoomImage.aspx?Categoryid=' + catid + '&pageIndex=' + curpg + '&RowPerPage=100&RowCnt=0&PgCnt=0&PgInfo=0'),'zoomimage','status=no,width=550,height=500, resizable= no, scrollbars=Yes, toolbar=no,location=no,menubar=no,left=200,top=20','');

Wednesday, May 21, 2008

Shopping Cart With Session

Imports System.Data
Partial Class ViewCart
Inherits System.Web.UI.Page
Dim objDT As System.Data.DataTable
Dim objDR As System.Data.DataRow
Public Total As Decimal

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
If Session("StartCart") = Nothing Then
makeCart()
AddToCart(Nothing, Nothing)
GetItemTotal()
Else
objDT = Session("Cart")
Dim itemCount As String = objDT.Rows.Count
Dim sessICount() As String = Session.Item("Product").Split(",")
If itemCount <> sessICount.Length Then
'--------
Dim i As Integer = 0
For i = (itemCount) To sessICount.Length - 1
'Dim Product = a(i)
Dim adp_CartPrd As New ViewCartDsTableAdapters.Product_MasterTableAdapter
Dim tb_CartPrd As New ViewCartDs.Product_MasterDataTable
adp_CartPrd.FillProductByPId(tb_CartPrd, sessICount(i))
objDR = objDT.NewRow
objDR("Quantity") = 1
objDR("Image") = tb_CartPrd.Rows(0).Item("ProdImage")
objDR("Product") = tb_CartPrd.Rows(0).Item("ProdName")
objDR("Cost") = Decimal.Parse(123.5)
objDR("ProdId") = tb_CartPrd.Rows(0).Item("ProdId")
objDT.Rows.Add(objDR)
Session("Cart") = objDT
gvCart.DataSource = objDT
gvCart.DataBind()
GetItemTotal()
Next
'---------
Else
gvCart.DataSource = objDT
gvCart.DataBind()
GetItemTotal()
End If

End If
Else
Dim i As Integer
i = 0
makeCart()
For i = 0 To gvCart.Rows.Count - 1
Dim sess As String = Session("Product")
Dim a() As String = sess.Split(",")
Dim Product = a(i)
Dim adp_CartPrd As New ViewCartDsTableAdapters.Product_MasterTableAdapter
Dim tb_CartPrd As New ViewCartDs.Product_MasterDataTable
adp_CartPrd.FillProductByPId(tb_CartPrd, a(i))
objDR = objDT.NewRow
objDR("Quantity") = CType(gvCart.Rows(i).FindControl("textQuantity"), TextBox).Text
objDR("Image") = tb_CartPrd.Rows(0).Item("ProdImage")
objDR("Product") = tb_CartPrd.Rows(0).Item("ProdName")
objDR("Cost") = Decimal.Parse(123.5)
objDR("ProdId") = tb_CartPrd.Rows(0).Item("ProdId")
objDT.Rows.Add(objDR)
Next
Session("Cart") = objDT
gvCart.DataSource = objDT
gvCart.DataBind()
GetItemTotal()
End If
End Sub
Sub AddToCart(ByVal s As Object, ByVal e As EventArgs)
Dim sess As String = Session("Product")
Dim a() As String = sess.Split(",")
Dim i As Integer
i = 0
objDT = Session("Cart")
Session("StartCart") = "Start"
For i = 0 To a.Length - 1
Dim Product = a(i)
Dim adp_CartPrd As New ViewCartDsTableAdapters.Product_MasterTableAdapter
Dim tb_CartPrd As New ViewCartDs.Product_MasterDataTable
adp_CartPrd.FillProductByPId(tb_CartPrd, a(i))
objDR = objDT.NewRow
objDR("Quantity") = 1
objDR("Image") = tb_CartPrd.Rows(0).Item("ProdImage")
objDR("Product") = tb_CartPrd.Rows(0).Item("ProdName")
objDR("Cost") = Decimal.Parse(123.5)
objDR("ProdId") = tb_CartPrd.Rows(0).Item("ProdId")
objDT.Rows.Add(objDR)
Session("Cart") = objDT
gvCart.DataSource = objDT
gvCart.DataBind()
Next
End Sub
Function makeCart()
objDT = New System.Data.DataTable("Cart")
'objDT.Columns.Add("ID", GetType(Integer))
'objDT.Columns("ID").AutoIncrement = True
'objDT.Columns("ID").AutoIncrementSeed = 1
objDT.Columns.Add("ProdId", GetType(String))
objDT.Columns.Add("Image", GetType(String))
objDT.Columns.Add("Product", GetType(String))
objDT.Columns.Add("Quantity", GetType(Integer))
objDT.Columns.Add("Cost", GetType(Decimal))
Session("Cart") = objDT
Return ""
End Function
Function GetItemTotal() As Decimal
Dim intCounter As Integer
Dim decRunningTotal As Decimal
For intCounter = 0 To objDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
decRunningTotal += (objDR("Cost") * objDR("Quantity"))
Next
Total = decRunningTotal
Return decRunningTotal
End Function

Friday, May 16, 2008

Auto Table hight/width increment

--

Image split in multiple part in asp.net

-------step-1------------
Put asp:button and file uploder tool in .aspx pages
-------Step-2------------
Importt two class in aspx.vb page
-------------------------
Imports System.Web.UI.WebControls.Unit
Imports System.Drawing

-------Step-3------------
Now On code behind on button click event write following
------------------------
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim obj As Image
obj = Drawing.Image.FromFile("C:\Documents and Settings\user2\Desktop\1m.jpg")
SplitImage(obj, 3, 1)
' fun1(obj, 3)
End Sub
-------Step-4------------
Now On code behind on Call Function(SplitImage()) write following
-------------------------
Private Function SplitImage(ByVal wholeImage As Image, ByVal rows As Integer, ByVal columns As Integer) As Image()
Dim cellWidth As Single = CType(wholeImage.Width / columns, Single)
Dim cellHeight As Single = CType(wholeImage.Height / rows, Single)

' Create an array of RectangleF to hold the RectangleFs

' that define parts (cells) of the wholeImage.
Dim rectangleFs((rows * columns) - 1) As Drawing.RectangleF

' Fill RectangleFs array with RectangleF objects.
Dim currentRow As Single = 0

Dim currentColumn As Single = 0
Dim rectangleFIndex As Integer = 0

For currentRow = 0 To rows - 1
For currentColumn = 0 To columns - 1
Dim newRectangleF As New Drawing.RectangleF()

newRectangleF.X = currentColumn * cellWidth

newRectangleF.Y = currentRow * cellHeight

newRectangleF.Width = cellWidth

newRectangleF.Height = cellHeight

rectangleFs(rectangleFIndex) = newRectangleF

rectangleFIndex += 1

Next

Next

' Create an array of Images to contain the images

' that will be created from the wholeImage.
Dim images(rectangleFs.GetLength(0)) As Image

' Fill images array with Images.
Dim i As Integer = 0

For i = 0 To rectangleFs.GetUpperBound(0)
Dim newBitMap As New Drawing.Bitmap(CType(cellWidth, Integer), CType(cellHeight, Integer))
Dim bitMapGraphics As Drawing.Graphics = Graphics.FromImage(newBitMap)

bitMapGraphics.Clear(Color.Blue)

bitMapGraphics.DrawImage(wholeImage, newBitMap.GetBounds(GraphicsUnit.Pixel), rectangleFs(i), GraphicsUnit.Pixel)

images(i) = newBitMap

newBitMap.Save("C:\Documents and Settings\user2\Desktop\" + i.ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)

Next
Return images
End Function

Thursday, May 15, 2008

Crystal Report by specific id

------------1st-Step-----------
Put Crystal Report Page in Project
than add your Select Database column without any Filter(like query:select * from abc)
add column as you want
------------2nd-step-----------
Put on Page(.asp) with dropdown,crystal report viewer,with crystal report datasource
------------3rd-step----------
write following code in behind
------------------------------
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim rpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument
Dim path As String = Server.MapPath("~\CrystalRepot\CrystalReportById.rpt")

Dim datatbl As New Data.DataTable
Dim constr As String = "Data Source=dynaserver\webdb;Initial Catalog=SuratShopping;User ID=sa;Password=saadmin"
Dim conn As SqlConnection = New SqlConnection(constr)
Dim adp As SqlDataAdapter
Dim ds As DataSet
conn.Open()
'Dim state As String = DropDownList1.SelectedValue
adp = New SqlDataAdapter("select * from CompanyImages where CompanyId='" & DropDownList1.SelectedValue & "' ", conn)
ds = New DataSet()
adp.Fill(ds, "CompanyImages")

rpt.Load(path)
CrystalReportSource1.DataBind()

CrystalReportViewer1.ReportSource = rpt
rpt.SetDataSource(ds.Tables("CompanyImages"))
End Sub

Create Thumbnail Image By File Uplod

Dim objImage, objThumbnail As System.Drawing.Image
Dim strServerPath, strFileName As String
Dim shtWidth, shtHeight As Short
'get image folder path on server
strServerPath = "C:\Documents and Settings\user2\Desktop\1m.jpg"
'retrive name of file to resize from query string
strFileName = "C:\Documents and Settings\user2\Desktop\1m.jpg"
'retrive file ,or error.gif if not available
Try
objImage = Drawing.Image.FromFile(strFileName)
Catch
objImage = Drawing.Image.FromFile(strServerPath)
End Try
'retrive width
shtWidth = 50
'work out a proportion height from widht
shtHeight = objImage.Height / (objImage.Width / shtWidth)
'Create Thumbnail
objThumbnail = objImage.GetThumbnailImage(shtWidth, shtHeight, Nothing, System.IntPtr.Zero)
'send down to client show image in browser
Response.ContentType = "image/Jpeg"
'objThumbnail.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
objThumbnail.Save("C:\Documents and Settings\user2\Desktop\" + "ddc.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
'Tidy up
objImage.Dispose()
objThumbnail.Dispose()

Tuesday, May 13, 2008

DataList Paging Store Procedure

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[usp_GetCategoryProduct]

@CategoryId int,
@PageIndex int,
@RowsPerPage int,
@RowCount int OutPut,
@PageCount int Output,
@PageInfo varchar(250) Output

AS

Declare @StartRowIndex int;
Set @StartRowIndex = (@PageIndex * @RowsPerpage) + 1;

DECLARE @TempItems TABLE
(
ID int IDENTITY,
ProdId int
)

INSERT INTO @TempItems (ProdId)
SELECT Product_Master.ProdId
FROM Product_Master inner join companycategory
on product_master.prodcateid=companycategory.prodcateid
where categoryid=@Categoryid

Select @RowCount = count(*) from @TempItems;
Set @PageCount = @RowCount / @RowsPerPage;

if @PageIndex > @PageCount
raiserror ('Out of Page Index', 16,1) ;


Select @PageInfo =
'Showing ' +
ltrim(str(@startRowIndex)) + ' - ' +
case
when (@RowCount > (@startRowIndex + @RowsPerPage) - 1)
then ltrim(str(@startRowIndex + @RowsPerPage) - 1)
else
ltrim(str(@RowCount))
end
+ ' of ' +
ltrim(str(@RowCount));


Select *

FROM @TempItems t
Inner Join Product_Master ON Product_Master.ProdId = t.ProdId
Where t.ID between @startRowIndex AND (@startRowIndex + @RowsPerPage) - 1;

Monday, May 12, 2008

Auto Changed Image/Data

<%@ Page Language="VB" MasterPageFile="~/UserMaster.master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" title="Welcome To Surat Online Retail Store" %>






























Div1 Div2 Div3 Div4 Div5


Div1







Wednesday, May 7, 2008

Trigger

*************Insert Trigger*******************
USE [CustomerCare]
GO
/****** Object: Trigger [tri_ClientInqDtl] Script Date: 04/26/2008 12:06:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [tri_ClientInqDtl]
on [dbo].[ClientInqDtl]
AFTER INSERT
AS
Declare @ClientPrdId int,
@EmployeeId int,
@ClientInquiryDtl int

select @ClientInquiryDtl=ClientInquiryDtl from inserted
select @ClientPrdId=ClientPrdId from inserted
select @EmployeeId=EmployeeId from ClientPrdMaster where ClientPrdId=@ClientPrdId


BEGIN
Update ClientInqDtl set EmployeeId=@EmployeeId where ClientInquiryDtl=@ClientInquiryDtl
End
***************Delete Trigger*********************
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [tri_DeletePrdVersion]
ON [dbo].[ProductMaster]
AFTER DELETE
AS
Declare @ProductId int

select @ProductId=ProductId from Deleted
BEGIN
delete ProductVersion where Productid=@ProductId
END

Friday, April 18, 2008

Print Out Of Table

How to Print in ASP.NET 2.0

One of the most common functionality in any ASP.NET application is to print forms and controls. There are a lot of options to print forms using client scripts. In the article, we will see how to print controls in ASP.NET 2.0 using both server side code and javascript.
Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to window.print() that simulates the print button.
Note: I have not written this class and neither do I know the original author. I will be happy to add a reference in case someone knows.
C# using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;

public class PrintHelper
{
public PrintHelper()
{
}

public static void PrintWebControl(Control ctrl)
{
PrintWebControl(ctrl, string.Empty);
}

public static void PrintWebControl(Control ctrl, string Script)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
if (ctrl is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation = false;
if (Script != string.Empty)
{
pg.ClientScript.RegisterStartupScript(pg.GetType(),"PrintJavaScript", Script);
}
HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(ctrl);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.End();
}
}

VB.NET
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Text
Imports System.Web.SessionState

Public Class PrintHelper
Public Sub New()
End Sub

Public Shared Sub PrintWebControl(ByVal ctrl As Control)
PrintWebControl(ctrl, String.Empty)
End Sub

Public Shared Sub PrintWebControl(ByVal ctrl As Control, ByVal Script As String)
Dim stringWrite As StringWriter = New StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(stringWrite)
If TypeOf ctrl Is WebControl Then
Dim w As Unit = New Unit(100, UnitType.Percentage)
CType(ctrl, WebControl).Width = w
End If
Dim pg As Page = New Page()
pg.EnableEventValidation = False
If Script <> String.Empty Then
pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script)
End If
Dim frm As HtmlForm = New HtmlForm()
pg.Controls.Add(frm)
frm.Attributes.Add("runat", "server")
frm.Controls.Add(ctrl)
pg.DesignerInitialize()
pg.RenderControl(htmlWrite)
Dim strHTML As String = stringWrite.ToString()
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Write(strHTML)
HttpContext.Current.Response.Write("")
HttpContext.Current.Response.End()
End Sub
End Class

Step 2: Create two pages, Default.aspx and Print.aspx. Default.aspx will contain the controls to be printed. Print.aspx will act as a popup page to invoke the print functionality.
Step 3: In your Default.aspx, drag and drop a few controls that you would like to print. To print a group of controls, place them all in a container control like a panel. This way if we print the panel using our PrintHelper class, all the controls inside the panel gets printed.
Step 4: Add a print button to the Default.aspx and in the code behind, type the following code:
C#
protected void btnPrint_Click(object sender, EventArgs e)
{
Session["ctrl"] = Panel1;
ClientScript.RegisterStartupScript(this.GetType(), "onclick", "");
}
VB.NET
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
Session("ctrl") = Panel1
ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "")
End Sub
The code stores the control in a Session variable to be accessed in the pop up page, Print.aspx. If you want to print directly on button click, call the Print functionality in the following manner :

PrintHelper.PrintWebControl(Panel1);

Step 5: In the Page_Load event of Print.aspx.cs, add the following code:
C#

protected void Page_Load(object sender, EventArgs e)
{
Control ctrl = (Control)Session["ctrl"];
PrintHelper.PrintWebControl(ctrl);
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim ctrl As Control = CType(Session("ctrl"), Control)
PrintHelper.PrintWebControl(ctrl)
End Sub

Thursday, April 17, 2008

Hot To Set Property in User-Control

-------Back-End Code-----------

Partial Class UserControls_CompanyDetail
Inherits System.Web.UI.UserControl
Private _CompanyId As Integer = 0

Public Property CompanyId() As Integer
Get
Return _CompanyId
End Get
Set(ByVal value As Integer)
_CompanyId = value
DataSrcCompanyDetail.SelectParameters("Cid").DefaultValue = value
frmCompDetails.DataBind()
End Set
End Property

End Class
-----------------------------------
------Source-Code-----------------
----------------------------------
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="CompanyDetail.ascx.vb"
Inherits="UserControls_CompanyDetail" %>





DataKeyNames="CompanyId" DataSourceID="DataSrcCompanyDetail"
CellPadding="0" Width="100%" HorizontalAlign="Center" EnableViewState="false">























































<%# Eval("CompName") %>

Address:

<%# EVal("CompAddress") %>
,
<%# Eval("AreaName") %>


<%# EVal("CompCity") %>
-
<%# EVal("CompPin") %>


<%# EVal("CompState") %>

 

Telephone:

<%#Eval("CompTelNo")%>

Fax:

<%#Eval("CompFax")%>

E-mail:

<%#Eval("CompEmail")%>

 

Key Person:

<%#Eval("ContactPerson")%>

Mobile No

<%#Eval("MobileNo")%>

 

Keywords:

<%#Eval("Keywords")%>

 

Description:

<%#Eval("BriefInfo")%>




SelectMethod="GetCompanyById" TypeName="MainDatasetTableAdapters.CompanyDetailTableAdapter" EnableViewState="false">




Calender Popup Calender

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="DateUserControl.ascx.vb"
Inherits="UserControls_DateUserControl" %>









onclientClick="javascript:GetDate1('<%=txtDate.ClientId%>'




ControlToValidate="txtDate" CssClass="ErrorMessage" EnableViewState="False" Display="Dynamic">
ErrorMessage="Date not valid" Display ="Dynamic" ValidationExpression ="^((((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9]))))[\-\/\s]?\d{2}(([02468][048])|([13579][26])))|(((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))[\-\/\s]?\d{2}(([02468][1235679])|([13579][01345789]))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$">

Feed Reader/Rss Reader

Step.1:.....Path Of Rss
Private Sub ReadNews()
Dim rd As New FeedReader("http://news.google.co.in/news?hl=en&ned=in&q=surat&ie=UTF-8&as_drrb=q&as_qdr=w&as_mind=14&as_minm=11&as_maxd=21&as_maxm=11&output=rss")
'Dim rd As New FeedReader("http://www.easy-indian-food.com/Indian-cooking.xml")
'Dim rd As New FeedReader("http://content.msn.co.in/rsscache/healthfitness.rss")
DataList1.DataSource = rd.GetDataTable
DataList1.DataBind()
End Sub
--------------------------
Step.2:.....Class1
-------------------------
Imports Microsoft.VisualBasic

Public Class FeedReader
Private mvarTable As Data.DataTable
Private mvarObjColl As FeedCollection
Private mvarSourceFile As String

Sub New()
mvarObjColl = New FeedCollection
End Sub

Sub New(ByVal SourceFile As String)
Me.New()
ReadFile(SourceFile)
End Sub

Public Overloads Sub ReadFile(ByRef SourceFile As String)
mvarSourceFile = SourceFile
ReadFile()
End Sub

Public Overloads Sub ReadFile()
Dim _TmpDS As New Data.DataSet
'If System.IO.File.Exists(SourceFile) Then
_TmpDS.ReadXml(mvarSourceFile)
If Not (_TmpDS.Tables("item") Is Nothing) Then
mvarTable = _TmpDS.Tables("item")
End If
_TmpDS = Nothing
PopulateCollection()
'End If
End Sub

Private Sub PopulateCollection()
mvarObjColl.clear()
For Each _TmpRow As Data.DataRow In mvarTable.Rows
mvarObjColl.Add(New Feed(_TmpRow("title").ToString(), _TmpRow("link").ToString(), _TmpRow("pubDate").ToString, _TmpRow("description").ToString()))
Next
End Sub

Public Function GetDataTable() As Data.DataTable
Return mvarTable
End Function

Public ReadOnly Property Items() As FeedCollection
Get
Return mvarObjColl
End Get
End Property

Public Property SourceFile() As String
Get
Return mvarSourceFile
End Get
Set(ByVal value As String)
mvarSourceFile = value
End Set
End Property
End Class
---------------------------
Step.3: class2
---------------------------
Imports Microsoft.VisualBasic

Public Class FeedCollection
Private mvarObjCollection As Collection

Public Sub New()
mvarObjCollection = New Collection
End Sub

Public Overloads Sub Add(ByRef Value As Feed)
mvarObjCollection.Add(Value)
End Sub

Public ReadOnly Property Count() As Integer
Get
Return mvarObjCollection.Count
End Get
End Property

Public Sub Remove(ByVal IndexNo As Integer)
mvarObjCollection.Remove(IndexNo)
End Sub

Public ReadOnly Property Item(ByVal IndexNo As Integer) As Feed
Get
Return CType(mvarObjCollection(IndexNo), Feed)
End Get
End Property

Public Sub Clear()
mvarObjCollection.Clear()
End Sub
End Class
---------------------------------
step:3:Class 3
---------------------------------
Imports Microsoft.VisualBasic

Public Class Feed
Private mvarTitle As String
Private mvarLinkURL As String
Private mvarTime As String
Private mvarContent As String

Sub New(ByVal valTitle As String, ByVal valLinkURL As String, ByVal valPublishTime As String, ByVal valContent As String)
mvarTitle = valTitle
mvarLinkURL = valLinkURL
mvarTime = valPublishTime
mvarContent = valContent
End Sub

Public Property Title() As String
Get
Return mvarTitle
End Get
Set(ByVal value As String)
mvarTitle = value
End Set
End Property

Public Property LinkURL() As String
Get
Return mvarlinkURL
End Get
Set(ByVal value As String)
mvarlinkURL = value
End Set
End Property

Public Property PublishTime() As String
Get
Return mvarTime
End Get
Set(ByVal value As String)
mvarTime = value
End Set
End Property
Public Property Content() As String
Get
Return mvarContent
End Get
Set(ByVal value As String)
mvarContent = value
End Set
End Property
End Class

SendMail Class

Public Class SendEmail

Public Sub SendEmails(ByVal strFromAdd As String, ByVal strToAdd As String, ByVal strMessage As String, ByVal strSubject As String)
Dim sendMail As New MailMessage
sendMail.IsBodyHtml = True
sendMail.Subject = strSubject
sendMail.To.Add(strToAdd)
sendMail.From = New MailAddress(strFromAdd)
sendMail.Body = strMessage
Dim clent As New SmtpClient
clent.Host = "suratshopping.com"
'clent.Send(sendMail)
End Sub
End Class

Create Thumbnail Image

Imports Microsoft.VisualBasic
Imports System.Drawing
Imports System.Drawing.Imaging

Public Class ThumbnailCreator

Public Shared Function CreateThumbnail(ByVal lcFilename As String, ByVal lnWidth As Integer, ByVal lnHeight As Integer) As Bitmap

Dim bmpOut As System.Drawing.Bitmap = Nothing
Try

Dim loBMP As New Bitmap(lcFilename)

Dim loFormat As ImageFormat = loBMP.RawFormat

Dim lnRatio As Decimal

Dim lnNewWidth As Integer = 0

Dim lnNewHeight As Integer = 0

'If the image is smaller than a thumbnail just return it

If (loBMP.Width < lnWidth And loBMP.Height < lnHeight) Then
Return loBMP
End If

If (loBMP.Width > loBMP.Height) Then
lnRatio = CType((lnWidth / loBMP.Width), Decimal)
lnNewWidth = lnWidth

Dim lnTemp As Decimal = loBMP.Height * lnRatio
lnNewHeight = CInt(lnTemp)
Else
lnRatio = CType((lnHeight / loBMP.Height), Decimal)

lnNewHeight = lnHeight

Dim lnTemp As Decimal = loBMP.Width * lnRatio
lnNewWidth = CInt(lnTemp)
End If

bmpOut = New Bitmap(lnNewWidth, lnNewHeight)

Dim g As Graphics = Graphics.FromImage(bmpOut)

g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic

g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight)

g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight)

loBMP.Dispose()


Catch
Return Nothing
End Try
Return bmpOut
End Function


End Class

Check Image Resolution In Asp.net

Imports Microsoft.VisualBasic
Public Class CheckImage
Public Function CheckImage(ByVal File As FileUpload, ByVal Size As Integer, ByVal width As Integer, ByVal Height As Integer, ByVal ImgOf As String) As Boolean
Dim sizes As String = File.PostedFile.ContentLength
Dim sizeKb As String = sizes / 1024
If ImgOf <> "Advertise" Then
Dim uploadimage As System.Drawing.Image = System.Drawing.Image.FromStream(File.PostedFile.InputStream)
Dim uploadimagewidth As String = uploadimage.PhysicalDimension.Width
Dim uploadimageheight As String = uploadimage.PhysicalDimension.Height
If ImgOf = "ShopImage" Then
If sizeKb <= Size And uploadimagewidth <= width And uploadimageheight <= Height Then
Return True
Else
Return False
End If
ElseIf ImgOf = "ProductImg" Then
If sizeKb <= Size And uploadimageheight <= Height Then
Return True
Else
Return False
End If
ElseIf ImgOf = "offer" Then
If sizeKb <= Size And uploadimagewidth <= width And uploadimageheight <= Height Then
Return True
Else
Return False
End If
End If
ElseIf ImgOf = "Advertise" Then
Return True
End If
End Function
End Class

Image store to Web-Folder Class

Imports Microsoft.VisualBasic
Public Class StoreToFolder
Function WebFolderImg(ByVal FileUploadId As FileUpload, ByVal FolderName As String, ByVal FileName As String, ByVal Operation As String) As String
If Operation = "Insert" Then
Dim NewFileName As String = ""
Dim File As String = System.IO.Path.GetFileName((FileUploadId).PostedFile.FileName)
Dim extension As String = System.IO.Path.GetExtension((FileUploadId).PostedFile.FileName)
'*** Add File To Web-Folder
NewFileName = Format(Now(), "ddMMyyHHmmss") + extension
Dim Path As String
Path = HttpContext.Current.Server.MapPath("..\" + FolderName + "\") + NewFileName
FileUploadId.SaveAs(Path)
Return NewFileName
ElseIf Operation = "InsertProduct" Then
Dim NewFileName As String = ""
Dim File As String = System.IO.Path.GetFileName((FileUploadId).PostedFile.FileName)
Dim extension As String = System.IO.Path.GetExtension((FileUploadId).PostedFile.FileName)
'*** Add File To Web-Folder
NewFileName = FileName + Format(Now(), "ddMMyyHHmmss") + extension
Dim Path As String
Path = HttpContext.Current.Server.MapPath("..\" + FolderName + "\") + NewFileName
FileUploadId.SaveAs(Path)
Return NewFileName
ElseIf Operation = "Delete" Then
Dim DeletedFile As String = HttpContext.Current.Server.MapPath("..\" + FolderName + "\" + FileName)
System.IO.File.Delete(DeletedFile)
End If
Return ""
End Function
End Class

Select Insert Update Delete By Store Procedurr

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


-- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[MyStoreProcedure]
-- Add the parameters for the stored procedure here
--<@Param1, sysname, @p1> = ,
--<@Param2, sysname, @p2> =
@Operation int,
@Parameter varchar(2),
@Uname varchar(10) ,
@Passoword int,
@RegisterStatus int,
@RegisterStatus1 int
AS
BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
if @Operation=1
begin
Select * from ddc order by Uname
end
if @Operation=2
-- Insert statements for procedure here
begin
insert into ddc ([Uname],[Passoword],[RegisterStatus],[RegisterStatus1])values(@Uname,@Passoword,@RegisterStatus,@RegisterStatus1)
end
if @Operation=3
begin
delete from ddc where Uname=@Uname
end
if @Operation=4
begin
Update [ddc] set [Uname]=@Uname,[Passoword]=@Passoword,[RegisterStatus]=@RegisterStatus,[RegisterStatus1]=@RegisterStatus where ([Uname]=@Uname)
end
END

Get 3-table data without Inner-Join

select AdvertisementMst.*,AdPosition.PageId,AdPosition.Position,PageMaser.PageName
from AdvertisementMst,AdPosition,PageMaser
where AdvertisementMst.AdPositionId=AdPosition.AdPositionId and
AdvertisementMst.AdvertisementMstId=@AdvertisementMstId

My Sql ServerQuery

--BetweenStatment
select CompName,OfferValidity from CompanyMaster where Offervalidity between '04/19/2008' and '04/21/2008' order by compname
--DistinceStatement
select distinct offerValidity from CompanyMaster
select AdvertisementMst.*,AdPosition.PageId,Adposition.Position,PageMaser.PageName
from AdvertisementMst,AdPosition,PageMaser
where AdvertisementMst.AdvertisementMstId=AdPosition.AdPositionId
--In StateMent
select * from CompanyMaster Where CompName In('2Much','Dhaval Super Store')
--LikeOrSearchKeyWord StateMent
select * from CompanyMaster where CompName like ('%2Much%')
--SoundEx Search StateMent
select * from CompanyMaster Where SoundEx(compname)= soundex('2Much')
--OrderBy Statement
--Assending Order
select * from CompanyMaster order by CompName asc
--Desending Order
select * from CompanyMaster order by CompName desc
--Count statement with Join Statement
select count(ProductMaster.ProductId) TotalProduct ,CompanyMaster.CompName from CompanyMaster,ProductMaster where CompanyMaster.companyId=35 and CompanyMaster.CompanyId=ProductMaster.Companyid group by CompanyMaster.CompName
--Alias StateMent
select tbl .CompName from CompanyMaster tbl
--Outer Join State ment
SELECT A1.store_name, SUM(A2.Sales) SALES
FROM Geography A1, Store_Information A2
WHERE A1.store_name = A2.store_name (+)
GROUP BY A1.store_name
--Concate Statement :Get Two ColumnData In On Column
select CompCity+''+CompName companyNameWithCity from CompanyMaster
--SubString Statement:Get Data of column with Specific Char limit
select Substring(CompName,1,3) CompPrefix from companyMaster
--Create View Statement: Get Data of Two Table in diffrent Column
create view Company_Product as select count(productMaster.ProductId) ProductCount,companyMaster.Compname CompanyName from companymaster,productmaster where companymaster.companyId=productmaster.companyId group by companymaster.compname
--Create index statement:
create index CompanyIndex on companyMaster(Compname,CompanyId)
--Alter Table
ALTER table customer add Gender char(1)
--Drop Table
DROP TABLE customer
--Truncat Table(Data only deleted from table
TRUNCATE TABLE customer
--Update statement
UPDATE Store_Information
SET Sales = 500
WHERE store_name = "Los Angeles"
AND Date = "Jan-08-1999"
--Delete statement
DELETE FROM Store_Information
WHERE store_name = "Los Angeles"

Regulare Expression For Calender(2001-2099)

runat ="server"
ControlToValidate ="txtDate"
SetFocusOnError ="true"
ErrorMessage="Date not Valid"
Display ="Dynamic"
ValidationExpression ="^((((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9]))))[\-\/\s]?\d{2}(([02468][048])|([13579][26])))|(((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))[\-\/\s]?\d{2}(([02468][1235679])|([13579][01345789]))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$">

Monday, March 17, 2008

Create Thumbnail image

Protected Sub btnCreatThumb_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreatThumb.Click
Dim objImage, objThumbnail As System.Drawing.Image
Dim strServerPath, strFileName As String
Dim shtWidth, shtHeight As Short
'get image folder path on server
strServerPath = "C:\Documents and Settings\user2\Desktop\aajanachle1.jpg"
'retrive name of file to resize from query string
strFileName = "C:\Documents and Settings\user2\Desktop\aajanachle1.jpg"
'retrive file ,or error.gif if not available
Try
objImage = Drawing.Image.FromFile(strFileName)
Catch
objImage = Drawing.Image.FromFile(strServerPath)
End Try
'retrive width
shtWidth = 50
'work out a proportion height from widht
shtHeight = objImage.Height / (objImage.Width / shtWidth)
'Create Thumbnail
objThumbnail = objImage.GetThumbnailImage(shtWidth, shtHeight, Nothing, System.IntPtr.Zero)
'send down to client show image in browser
Response.ContentType = "image/Jpeg"
'objThumbnail.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
objThumbnail.Save("C:\Documents and Settings\user2\Desktop\" + "ddc.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
'Tidy up
objImage.Dispose()
objThumbnail.Dispose()
End Sub

Wednesday, March 5, 2008

GridView Specific Row Color Through DataBase

-------------------------
Grid Pager Text Visible False
-------------------------
Protected Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
Dim topRow As GridViewRow = GridView1.TopPagerRow
Dim bottomRow As GridViewRow = GridView1.BottomPagerRow

If (GridView1.PageIndex) = 0 Then
CType(topRow.FindControl("lbPrevious"), LinkButton).Enabled = False
CType(topRow.FindControl("lbPrevious"), LinkButton).CssClass = "DisableLink"

CType(bottomRow.FindControl("lbPrevious"), LinkButton).Enabled = False
CType(bottomRow.FindControl("lbPrevious"), LinkButton).CssClass = "DisableLink"
End If

If (GridView1.PageIndex + 1) = GridView1.PageCount Then
CType(topRow.FindControl("lbNext"), LinkButton).Enabled = False
CType(topRow.FindControl("lbNext"), LinkButton).CssClass = "DisableLink"

CType(bottomRow.FindControl("lbNext"), LinkButton).Enabled = False
CType(bottomRow.FindControl("lbNext"), LinkButton).CssClass = "DisableLink"
End If
End Sub
---------------------------------------------------------------------------
Grid view Row Color specifice with database
----------------------------------------------------------------
Protected Sub gvSelectesdShop_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvSelectesdShop.RowDataBound
' 'If e.Row.RowType = DataControlRowType.DataRow Then
' ' Dim status As Boolean = CType(e.Row.FindControl("Status"), Label).Text
' ' If status = False Then
' ' e.Row.BackColor = Drawing.Color.AntiqueWhite
' ' e.Row.ToolTip = "This Shop is not approved yet!"
' ' End If
' 'End If
'End Sub

Friday, February 29, 2008

Wednesday, February 27, 2008

Regular Expresion for FileUpdload

ID="FileToUpload"
runat="server"
ValidationGroup="Second"
Width="274px"
Font-Names="Verdana" />
*
ID="FileUploadValidator"
runat="server"
ControlToValidate="FileToUpload"
ErrorMessage="Upload PDF files only"
ValidationGroup="Second"
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG)$"
Width="152px"
Font-Bold="True"
EnableViewState="False">

ID="RequiredFieldValidatorDocument"
runat="server"
ValidationGroup="Second"
ErrorMessage="Select a document to upload"
ControlToValidate="FileToUpload"
Font-Bold="True">

id="ButtonAddFile"
runat="server"
ValidationGroup="Second"
Height="23px"
Width="125px"
Text="Upload Document"
Font-Names="Verdana" />