Friday, December 26, 2008

Fill DropDownList By Using Professional Ajax (AjaxMethod Attribute and CallBack)

Hi..
Today I am going to post a very Basic but very important example .This is the example of the professional Ajax showing the usage of the "[Ajax.AjaxMethod()]" attrubute.
Here in this example i am just showing a string message and bind a dropdownList in javascript by calling the server side methods in javascript.
This is very basic example You can modify it according to your need .
Before doing all this you have to add refernce of ajax.dll in bin folder.
you can download the a sample project from HERE . This Project includs the ajax.dll also. you can get the dll from this link by downloading the sample project.

The step taken in this example are as given below.


Step 1.) Modification in web.config file
put the "< add verb="POST,GET...." in the HttpHandlers section in web.config as given below.

[system.web]
[httpHandlers]
[add verb="POST,GET" path="ajax/*.ashx"
type="Ajax.PageHandlerFactory, Ajax"/]
[/httpHandlers]


Step 2.) Make the AjaxMethod which we have to call in Javascript in Desgn file of the page Suppose we have the page
Test1.aspx in the folder "Sanjeev" (Sanjeev/Test1.aspx)
so the .cs file of the page looks like as given below..
Here the important things are :
A.) Ajax.Utility.RegisterTypeForAjax(typeof(Sanjeev_Test1));
Where "Sanjeev_Test1" is the Name of the ppartial class of the page.
B.) We have to put "[Ajax.AjaxMethod()]" attrubute before the method body.
=========================================================
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
public partial class Sanjeev_Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(Sanjeev_Test1));
}
[Ajax.AjaxMethod()]
public string GetName()
{
//to alert the simple string message to test
return "Sanjeev Kumar Chauhan";
}
[Ajax.AjaxMethod()]
public DataSet getDataSet()
{
//use to get the DataSet by which we have to bind the
//DropdownList
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn dcText = getDataColumn("Text");
DataColumn dcValue = getDataColumn("Value");
dt.Columns.Add(dcText);
dt.Columns.Add(dcValue);
string strName = "Name";
string strValue = "sanjeev";
for (int i = 0; i < 6; i++)
{
DataRow dr = dt.NewRow();
dr[dcText] = strName + i.ToString();
dr[dcValue] = strValue + i.ToString();
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
return ds;
}
public DataColumn getDataColumn(string ColName)
{
DataColumn dc = null;
dc = new DataColumn(ColName, System.Type.GetType("System.String"));
return dc;
}
}
==================================================
3.) the aspx file of the page :

[%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Sanjeev_Test1" %]
[!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"]
[html xmlns="http://www.w3.org/1999/xhtml" ]
[head id="Head1" runat="server"]
[title]Untitled Page[/title]
[script language="javascript" type="text/javascript"]
// function GetTasks() //Using Call Back
// {
// Sanjeev_Test1.GetName(GetName_CallBack);
// }
//function GetName_CallBack(response)//The CallBack function
// {
// alert(response.value);
// return false;
// }
// Without Using Call Back this also works properly
function GetTasks()
{
var str = Sanjeev_Test1.GetName();
alert(str.value);
}
function getDS()
{
var resp = Sanjeev_Test1.getDataSet();
var ds = resp.value;
if(ds.Tables[0].Rows.length == 0 )
{

// document.getElementById("ddl").options.length=0;
alert("There is no Term");
}
else
{
document.getElementById("ddl").options.length=0;
if(ds.Tables[0].Rows.length ] 0 )
{
for(var i=0; i[ds.Tables[0].Rows.length; i++)
{
var o = document.createElement("option");
o.value = ds.Tables[0].Rows[i].Value;
o.text = ds.Tables[0].Rows[i].Text;
document.getElementById('ddl').add(o);
}
}
}
}
[/script]
[/head]
[body]
[form id="form1" runat="server"]
[div]
[input type="button" id="btnHTML" value="ShowName" onclick="return GetTasks();" /]
[br /]
[input type="button" value="Fill DropDown" onclick="getDS();" /]
[asp:DropDownList ID="ddl" runat="server"]
[/asp:DropDownList]
[/div]
[/form]
[/body]
[/html]
================================================================
I hope you will enjoy this.
Thanks :
Sanjeev Kumar
HelpOnDeskTeam

Monday, December 22, 2008

Show Formatted Date And Time Using Java Script...

Hello...
Today , I m here to give an example how to get the formated Date And Time using Java Script, and the Format is Like "Mon Dec 22 2008 10:52:07 PM" . so have a look on the following example...

function ShowFormattedDateAndTime()
{
var now = new Date() ;
var time=now.toLocaleTimeString();
var dayname=now.toDateString();
var totaldaytime=dayname+" "+time;
document.getElementById("Lbl").innerHTML="Draft Auto Saved at " + totaldaytime;
}


Sanjeev Kumar
HelpOn Desk Team

Friday, December 19, 2008

How to check the Date Format Using SQL SERVER 2005

Hello ...
Today , I am presenting a very Good Stored procedure as well as the UseDefined funtion and its use in the stored procedure the date formate is MM/DD/YYYY.
-- The Procedure is Used to get the Data For Event start date,Begin Time and End Time.
CREATE proc [dbo].[usp_GetEventDateTime]
(
@eventId uniqueidentifier
--The EventId corresponds to which we have to get data
)
AS
BEGIN
Select eventDateTimeId, eventDate, beginTime, endTime
,dbo.udf_IsValidEventStartTimeFormat(beginTime) As 'StartTimeFormat', dbo.udf_IsValidEventEndTimeFormat(endTime) As 'EndTimeFormat'
From EventDateTime
Where eventId = @eventId
--dbo.udf_IsValidEventStartTimeFormat is used to get the correct format of the Time
END
The UserDefined Functio IsValidEventStartTimeFormatn Is Geven As Given Below:

============================================================================
CREATE FUNCTION [dbo].[udf_IsValidEventStartTimeFormat] (@beginTime varchar(50))
RETURNS smallint
AS
BEGIN
Declare @ReturnVal smallint
Set @ReturnVal = 1
If @beginTime = '' Or @beginTime IS NULL Or
CharIndex(':',@beginTime) <> 3 Or
CharIndex(' ',@beginTime) <> 6 Or
Len(SubString(@beginTime,CharIndex(' ',@beginTime)+1,Len(@beginTime))) != 2 Or
SubString(@beginTime,CharIndex(':',@beginTime)+1,1) = ' ' Or
isnumeric(substring(@beginTime,0,CharIndex(':',@beginTime))) !=1 Or
isnumeric(SubString(@beginTime,CharIndex(':',@beginTime)+1, CharIndex(' ',@beginTime) - (CharIndex(':',@beginTime)+1) ) ) !=1
Set @ReturnVal = 0 -- If not valid time format (HH:MM AM/PM)
RETURN @ReturnVal
END
With Love..
Sanjeev Chauahn
HelpOnDesk Team

Wednesday, December 17, 2008

Display On Status Bar Of the Browser Window

Hi ...

Hi this time I am here with some easy wonder of java script . when you play with this I am sure you will enjoy this.

The 1st one is About :When we want to display the current Time in Status Bar. then You have to call the following java script function whereEver you need(Generally It will be called onload of the body in HTML)



function ShowTime()
{
var TimerKey
var now = new Date()
var Hours = now.getHours()
var Minutes = now.getMinutes()
var Seconds = now.getSeconds()
var TimeDisplay = document.getElementById("lblTime");
TimeDisplay.innerText = ((Hours > 12) ? Hours - 12 : Hours) + ((Minutes <> 12) ? " PM" : " AM")
window.status = ((Hours > 12) ? Hours - 12 : Hours) + ((Minutes <> 12) ? " PM" : " AM")
TimerKey = setTimeout("ShowTime()",1000)
}


var messageNum = 0;
function messageChanger()
{
if (messageNum ==0) {
defaultStatus = "Welcome to our Blog...";
messageNum = 1;
}
else
{
defaultStatus = "C#,JavaScript Articles";
messageNum = 0;
}
//Schedule the next message
setTimeout("messageChanger();", 3000);
}

And the 2nd one is About :When we want to display our Custom Message in Status Bar. then You have to call the following java script function whereEver you need(Generally It will be called onload of the body in HTML)

2.)


var messageNum = 0;
function messageChanger()
{
if (messageNum ==0) {
defaultStatus = "Welcome to our Blog...";
messageNum = 1;
}
else
{
defaultStatus = "C#,JavaScript Articles";
messageNum = 0;
}
//Schedule the next message
setTimeout("messageChanger();", 3000);
}

Thanks :

Sanjeev Chauhan

HelpOn Desk Team

Tuesday, December 16, 2008

use checkboxlist as checkboxsradiolist in javaScript

Hello,
In this week I got a very intresting problem and for solving it we have to use JAVAScript.
look a simple view on problem. we are using the checkbox list for selection cretieria.
we have 5 checkbox list but 2 check box list used as an radiobutton list. means user can select
one option at a time and his previous selection must be show until he choose the other next
choice.
Other three are simple in which new selction is added as we do by default.
so consentrate on problem. for solveing it i created function saveMouserOverID(control)
which get the id of control where mouse jump upon the control.
and after it created a javascript fucntion CheckUnCheckBox(crtl) wehre if control goes in to
default case it will unchech all check box expect the currently clicked check box.
b'cz this id is stored in saveMouseOverFunction();
view of the code is follows.
We can also store that id in hiddenfield and first uncheckall the checkbox and after it check
the control where id is stored in hidden field.

Thanks
HElpOnDesk Team


structure of checkboxList

[asp:CheckBoxList onClick="return CheckUnCheckBox('ssss');" ID="RS" OnSelectedIndexChanged="dosomeserverside"
RepeatColumns="setIntasuwant" CellSpacing="setIntasuwan"
runat="server" AutoPostBack="True"]
[asp:ListItem onmouseover="javascript:saveMouserOverID('0')" Text="select ALL" Value="Selectall"][ /asp:ListItem]
[asp:ListItem onmouseover="javascript:saveMouserOverID('1')" Text="helpindesk" Value="Helpondesk"][ /asp:ListItem]
[asp:ListItem onmouseover="javascript:saveMouserOverID('2')" Text="sanjeev"
Value="Sanjeev"][ /asp:ListItem]
[ /asp:ChekcBoxList/]


function saveMouserOverID(control)
{
controlid=control;

}

function CheckUnCheckBox(ctrl)
{
var checkbox = document.getElementById('ctl00_ContentPlaceHolder1_'+ctrl);
var inputlist = checkbox.getElementsByTagName("input");
var i=0;
var id;
switch(ctrl)
{
case "shape":
for(i=0; i[inputlist.length; i++)
{
//id = 'checkImage'+(parseInt(i)+parseInt('4'));
if(inputlist[i].checked)
{
if(controlid == 0 && controlid != i)
{
inputlist[i].checked = '';
// document.getElementById(id).src=imgFalse;
}
else if(controlid !=0 && i==0)
{
inputlist[i].checked = '';
//document.getElementById(id).src=imgFalse;
}
}
}
break;
case "color":
for(i=0; i[inputlist.length; i++)
{
//id = 'checkImage'+(parseInt(i)+parseInt('23'));
if(inputlist[i].checked)
{
if(controlid == 0 && controlid != i)
{
inputlist[i].checked = '';
//document.getElementById(id).src=imgFalse;
}
else if(controlid !=0 && i==0)
{
inputlist[i].checked = '';
//document.getElementById(id).src=imgFalse;
}
}
}
break;

default:
for(i=0; i[inputlist.length; i++)
{
// if(ctrl == 'weight')
// {
//
// }
// else if(ctrl == 'price')
// {
//
// }
if(inputlist[i].checked)
{
if(controlid != i)
{
inputlist[i].checked = '';

}
}
else
{
inputlist[i].checked = '';

}
}
}
}
[/script]

Friday, December 12, 2008

APPLY GOOGLE LIKE SEARCH STORED PROCEDURE

Hi..

Today I m posting a very good as well as very important Stored procedure which is used to apply the google type search in your data base here in this SP i am giving the IDs of the table in which i want to search.
Please have a look its very intersting..


CREATE PROCEDURE PROC_Google_Like_Search
(
@InputText varchar(100)
)
AS
BEGIN
SET NOCOUNT ON;

declare @SearchChar varchar(8000)
Set @SearchChar = '%'+ @InputText+ '%'--'%partner%'--, '11/11/2006'

declare @CMDMain varchar(8000), @CMDMainCount varchar(8000),@CMDJoin varchar(8000)
declare @ColumnName varchar(100),@TableName varchar(100)

declare dbTable cursor for
SELECT
Distinct b.Name as TableName
FROM
sysobjects b
WHERE id in ( 1195151303,1115151018,859150106) --*** see The Note Comment for this

-- b.type='u' and b.Name <> 'dtproperties'
--order by b.name
open dbTable
fetch next from dbTable into @TableName

WHILE @@FETCH_STATUS = 0
BEGIN
declare db cursor for
SELECT
c.Name as ColumnName
FROM
sysobjects b,
syscolumns c
WHERE
C.id = b.id and
b.type='u' and b.Name = @TableName
order by b.name

open db
fetch next from db into @ColumnName

set @CMDMain = 'SELECT ' + char(39) + @TableName + char(39) + ' as TableName,'+
' ['+ @TableName + '].* FROM [' + @TableName + ']'+
' WHERE '
set @CMDMainCount = 'SELECT Count(*) FROM [' + @TableName + '] Where '
Set @CMDJoin = ''

WHILE @@FETCH_STATUS = 0
BEGIN

set @CMDJoin = @CMDJoin + 'Convert(varchar(5000),[' +@ColumnName + ']) like ' + char(39) + @SearchChar + char(39) + ' OR '

fetch next from db into @ColumnName
end
close db
deallocate db

Set @CMDMainCount = 'If ('+ @CMDMainCount + Left(@CMDJoin, len(@CMDJoin) - 3)+ ') > 0 Begin '
Set @CMDMain = @CMDMainCount + @CMDMain + Left(@CMDJoin, len(@CMDJoin) - 3)
Set @CMDMain = @CMDMain + ' End '

Print @CMDMain

exec (@CMDMain)

fetch next from dbTable into @TableName
end
close dbTable
deallocate dbTable
END



***NOTE :-
To get the table id to be searched from the sysObject..
Select * from sysobjects where xtype='u' order by crdate desc



Thanks ...
Sanjeev Chauhan
HelpOnDesk Team

Code Help to Upload Image In Binary Format in SQL SERVER DB

Hi...

The coming post is about to How we can store image in to the database in a binary foramt.
we are very thankful to Mr. Shameem Pundeer for his kind supports ..And I hope it will be carry on in the future..


Color1 is Datagird name. On Updatecommand of datagrid we write code to upload vedio and image in sql-server database.

private void color1_UpdateCommand(object source, DataGridCommandEventArgs e)
{
int getItemID = Convert.ToInt32(color1.DataKeys[e.Item.ItemIndex]);
System.Web.UI.HtmlControls.HtmlInputFile File1 = (System.Web.UI.HtmlControls.HtmlInputFile)e.Item.Cells[0].Controls[1];
System.Web.UI.HtmlControls.HtmlInputFile File2 = (System.Web.UI.HtmlControls.HtmlInputFile)e.Item.Cells[1].Controls[1];
TextBox txt1 = (TextBox)e.Item.Cells[2].Controls[1];
TextBox txt2 = (TextBox)e.Item.Cells[3].Controls[1];


if(File1.Value != "")// to upload vedio file on sql-server database
{

string fpath = File1.PostedFile.FileName;
string fName = System.IO.Path.GetFileName(fpath);
string currPath = Request.PhysicalApplicationPath;
File1.PostedFile.SaveAs(currPath+ "/_video/" + fName);

string SqlUpdFName = "update item set fileName='" + fName + "'" + " where itemID=" + getItemID ;
int AffrowUpd = Convert.ToInt32(oDBManager.ExecuteNonQuery(SqlUpdFName));
}

if(File2.Value != "")// Upload image file to sql-server database in binary format
{
////////////////////Deleting Last Image Which has to Update////////////////////////
string SqlDelImg = "Delete from image where itemID =" + getItemID;
int rowAff3 = Convert.ToInt32(oDBManager.ExecuteNonQuery(SqlDelImg));

////////////////////////////////////////////////////////////////////////////////////

int len = File2.PostedFile.ContentLength;
double k = Convert.ToDouble(len);
byte[] pic = new byte[len];
File2.PostedFile.InputStream.Read (pic, 0, len);
string imgContentType = File2.PostedFile.ContentType;
string imgName1 = File2.Value;
SqlConnection Conn = new SqlConnection(@ConfigurationSettings.AppSettings["ConnectionString"]);

try
{
Conn.Open ();
SqlCommand cmd1 = new SqlCommand ("insert into image" + "(imageContent, imageType, imageName, imageSize, itemID) values (@imageContent,@imageType, @imageName, @imageSize, @itemID )", Conn);
cmd1.Parameters.Add ("@imageContent",pic );
cmd1.Parameters.Add ("@imageType", imgContentType);
cmd1.Parameters.Add ("@imageName", imgName1);
cmd1.Parameters.Add ("@imageSize", k);
cmd1.Parameters.Add("@itemID",getItemID);



cmd1.ExecuteNonQuery ();
}
finally
{
Conn.Close ();
}



}

if(txt1.Text != "")
{
string SqlUpdIName = "update item set itemName='" + txt1.Text + "'" + " where itemID=" + getItemID;
int affUpdRow1 = Convert.ToInt32(oDBManager.ExecuteNonQuery(SqlUpdIName));

}

if(txt2.Text != "")
{
string SqlUpdPrice = "update item set itemPrice=" + txt2.Text + " where itemID=" + getItemID;
int affUpdRow2 = Convert.ToInt32(oDBManager.ExecuteNonQuery(SqlUpdPrice));

}


color1.EditItemIndex = -1;
BindDataGrid();



}

Thanks:
Sanjeev Kumar
HelpOnDesk Team

Thursday, December 11, 2008

Getting Contant Page Value To Master Page

Hi..

Now I am going to describe How we can pass the value from content Page to its Master Page.
This code is given by One of my Best Friend Mr. Shameem Pundeer.

on master page:
< asp:Label ID="lblGetVal" Visible="false" runat="server" Text="0">
I want to get text value from content page then i have to write on content page as below
((Label)Master.FindControl("lblGetVal")).Text = Convert.ToString(star_overall);
//Where star_overall is a variable on .cs file of content page
//use this on master page

GetvalfromContant = Convert.ToInt32(lblGetVal.Text);




Enjoy Coding...
Sanjeev Chauhan
HelpOnDesk Team

Tuesday, December 9, 2008

JAVA SCRIPT IMAGE ROTATOR - SLIDE SHOW

Hi ..

Today I m going to describe you How we can do image ratation(slide Show as in flash),This is very simple and frankly I got it by googleing(he he he...).And you also enjoy this.

Here is the Code..


[html xmlns="http://www.w3.org/1999/xhtml" ]
[head runat="server"]
[title]Untitled Page[/title]

[script type="text/javascript" type="text/javascript"]

var image1=new Image()
image1.src="Images/4.JPG"
var image2=new Image()
image2.src="Images/5.JPG"
var image3=new Image()
image3.src="Images/6.JPG"

//variable that will increment through the images
var step=1
function slideit()
{
//if browser does not support the image object, exit.
if (!document.images)
return
document.images.slide.src=eval("image"+step+".src")
if (step[3)
step++
else
step=1
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}

[/script]
[/head]
[body onload="slideit();"]
[form id="form1" runat="server"]
[div]
[img src="Images/4.JPG" name="slide" width="300" height="156" /]
[/div]
[/form]
[/body]
[/html]



Enjoy the Image Rotating..

Sanjeev Chauhan
HelpOnDesk Team

Thursday, December 4, 2008

How to create and save the XML from a String in Server

Hello ...

Once Again I m here and presenting a post .This Post is really very good when You have to create an Xml file for the flash implemrntaion .You can use this.


protected void CreateXml()
{
XmlDocument empDoc = new XmlDocument();
Response.ContentType = "text/xml";
DataSet ds = getdata("test_GetXML");
XmlDocument UpcomeDoc = new XmlDocument();
Response.ContentType = "text/xml";
if (ds.Tables[0].Rows.Count > 0)
{
try
{
////Load the XML from a String
empDoc.LoadXml("" +
"" +
"First Name" +
"Last Name" +
"
City" +
// "WA99999" +
"
");
////Save the XML data onto a file
empDoc.Save(MapPath("EmployeesNew.xml"));
Response.Write(empDoc.InnerXml);
}
catch (XmlException xmlEx)
{
Response.Write("XmlException: " + xmlEx.Message);
}
catch (Exception ex)
{
Response.Write("Exception: " + ex.Message);
}
}
}


Thax....
Sanjeev Kumar
HelpOnDesk Team

Wednesday, December 3, 2008

Sending Mail Using SMTP Server Credentials

Hi..

Here you will find the quick reference of mail Sending.
have a look and enjoy..
==================================================================
The Class File Where The Email Manager class resides...
==================================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Configuration;
namespace CommonEmailManager
{
public class MailManager
{
private bool _issent;
private string _toAddress;
private string _strFileName;
public MailManager()
{
}
///
/// This Method Is used to send the mail
///

/// Contents of an e-mail
public void Send(MailContents emailcontents)
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //add port number 587
NetworkCredential mailAuth = new NetworkCredential("MyMaiId@gmail.com", "MyPwd");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = mailAuth;
MailAddress from = new MailAddress(emailcontents.FromEmailAddress, emailcontents.FromName);
MailAddress to = new MailAddress(ToAddress);
MailMessage message = new MailMessage(from, to);
message.Subject = emailcontents.Subject;
message.Body = emailcontents.Body;
message.IsBodyHtml = true;
if (emailcontents.FileName != null)
{
message.Attachments.Add(new Attachment(emailcontents.FileName));
}
try
{
client.Send(message);
IsSent = true;
}
catch (Exception ex)
{
throw ex;
}

}

///
/// This Method Is used to send the mail having with an attachment with it
///

/// Contents of an e-mail
public void SendAttachment(MailContents emailcontents)
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //add port number 587
NetworkCredential mailAuth = new NetworkCredential("MyMaiId@gmail.com", "MyPwd");
client.EnableSsl = true;client.UseDefaultCredentials = false;
client.Credentials = mailAuth;MailAddress from = new MailAddress(emailcontents.FromEmailAddress, emailcontents.FromName);
MailAddress to = new MailAddress(ToAddress);
MailMessage message = new MailMessage(from, to);
message.Subject = emailcontents.Subject;
message.Body = emailcontents.Body;
message.IsBodyHtml = true;
Attachment atch = new Attachment(emailcontents.FileName);
message.Attachments.Add(atch);
try
{
client.Send(message);
IsSent = true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
atch.Dispose();

}

}

public bool IsSent
{
get { return _issent; }
set { _issent = value; }
}
private string SMTPServerName
{
get { return ConfigurationManager.AppSettings["SMTPServer"]; }
}
public string ToAddress
{

get
{
return _toAddress;
}
set
{
_toAddress = value;
}

}
}
public struct MailContents
{
public string To;
public string FromName;
public string FromEmailAddress;
public string Subject;
public string Body;
public string FileName;

}

}


==================================================================

The Page code from where We send the Email ...And on Which WE call the emailManger.cs class methods.
==================================================================

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Data.SqlClient;
using System.Web.Mail;
using System.IO;
using CommonEmailManager;

public partial class Admin_AdminNewLetterSend : System.Web.UI.Page
{
//Do Your Code
protected void Page_Load(object sender, EventArgs e)
{
//Do Your Code
}

protected void btnSendmail_Click(object sender, EventArgs e)
{
string strMsg = string.Empty;
try
{
//targetEmailId will be get in any how...
SendingMail(targetEmailId);
strMsg = "The News Letter has been sent successfully...";
}
catch (Exception ex)
{
strMsg = "There is Some Error to send the newsletter this time .Please try again";
}
finally
{
ConfirmJScript(strMsg);
}
}
public void ConfirmJScript(string strMsg)
{
string JScript = "alert('" + strMsg + "');";
JScript = "";
ClientScript.RegisterStartupScript(this.GetType(), "JScript", JScript);
}
public void SendingMail(string TargetEmailId)
{
CommonEmailManager.MailManager emailmngr = new MailManager();
CommonEmailManager.MailContents contents = new MailContents();
string msgBody = "my Message Body(I May be HTML Body)";
contents.Body = msgBody;
contents.FromEmailAddress = "My EmailID@gmail.com";
contents.Subject = "My Meassage";
emailmngr.ToAddress = TargetEmailId;
emailmngr.Send(contents);
}

}
==================================================================

Enjoy mail Sending

Sanjeev Kumar
HelpOnDesk Team

Searching Filter With Dynamic Query

Hi.

I am little bit weak in the field of Data Base .Many of you know this yet I want to share a DB stored procedure with .This SP helps you as a template when you have to Get some data with filters.


CREATE Procedure [dbo].[AdminOngoingAuction]
(
@BidID as smallint=1 , ---ProductId as mortgage or car insurance
@State as varchar(20)='',
@City as varchar(50)='',
@Zipcode as varchar(50)='',
@BuyerFName as varchar(100)='',
@BuyerLName as varchar(100)='',
@OpeningDate as datetime=null,
@ClosingDate as datetime=null,
@BidTimes as varchar(20)='',
@LoanTerm as int=0,
@PropertyValue as money=0,
@ResidenceStatus as int=0, --Propery Use ID
@LoanPurpose as int=0,
@LoanAmount as money=0,
@StartingBid as varchar(100)='',
@CurrentBid as varchar(100)='',
@totalbids as int=-1,
@FiveMinueRule as int=0,
@FrontDebtRatio as varchar='', -----
@BackDebtRatio as varchar='', -----
@CompletedDate as datetime=null, -----
@MaxLTV as varchar(5)='', -----
@MinLTV as varchar(5)='', -----
@MaxFicoScore as varchar(5)='',
@MinFicoScore as varchar(5)='', ----
@SSN as Bigint=0,
@BuyerEmail as varchar(100)=''

)
as
Begin
declare @query as varchar(Max)

if (len(@State)>2)
select @State=statename from state where statefname=@state

set @query= 'select Distinct(AUC.loanrequestid),(''AUC0'' + convert(varchar,BOI.LoanRequestID)) as AuctionID,AUC.BuyerID,AUC.StartDate,AUC.EndDate,
(select count(id) from auction where loanrequestid=AUC.LoanRequestId and bid is not null) as Totalbids,
(select min(bid) from auction where loanrequestid=AUC.LoanRequestId) as Currentbid,
(select max(bidsubmitdate) from auction where loanrequestid=AUC.LoanRequestId) as latestBidTime,
BOI.BorrowerFirstName + '' '' + BOI.BorrowerLastName as BuyerName,
(select BUd.EmailID as BuyerEmail from buyernotification BN inner join BuyerDetails BUd
on BN.BuyerId = BUd.BuyerId where Mail =''1'' and AuctionDisabled =''1'')as BuyerEmail,
BOI.City, BOI.State, BOI.ZIPID,
MLT.LoanAmount, MLT.NoOfmonth as LoanTerm, BLP.OpeningBid as StartingBid, PRI.LoanPurposeID,
PRI.PropertyUseID, PRI.OriginalCost as PropertyValue, (MOT.MortgageType + '', '' + convert(varchar,MLT.NoOfmonth) + '', '' + LOP.LoanPurpose) as MortgageType, MOT.MortgageType, MLT.InterestRate,

PRT.PropertyType from Auction AUC
inner join borrowerinformation BOI on BOI.loanrequestid=AUC.loanrequestid
inner join buyerloanprofile BLP on BLP.loanrequestid=BOI.loanrequestid
inner join propertyinformation PRI on BLP.loanrequestid=PRI.loanrequestid
inner join PropertyType PRT on PRT.PropertyTypeID=PRI.PropertyTypeID
inner join MortgageLoanTerm MLT on MLT.loanrequestid=PRI.loanrequestid
inner join MortgageType MOT on MOT.MortgageTypeID=MLT.MortgageTypeID
inner join LoanRequest LOR on LOR.loanrequestid=PRI.loanrequestid
inner join LoanPurpose LOP on LOP.LoanID=PRI.LoanPurposeID
inner join BuyerDetails BUD on BUd.BuyerID=LOR.BuyerID

where AUC.IsDisabled is Null and AUC.IsCompleted is Null and AUC.IsChallenged is Null and AUC.adminstatus is Null
and BUD.bidtype=' + convert(varchar, @bidID)

if (@State <>'')
set @query= @query + 'and BOI.State=''' + @State + ''''
if(@City<>'')
set @query= @query + 'and BOI.city=''' + @City + ''''
if(@Zipcode<>'')
set @query= @query + 'and BOI.zipid=''' + @Zipcode + ''''
if(@BuyerFName<>'')
set @query= @query + 'and BOI.BorrowerFirstName=''' + @BuyerFName + ''''
if(@BuyerLName<>'')
set @query= @query + 'and BOI.BorrowerLastName=''' + @BuyerLName + ''''
if(@SSN>0)
set @query= @query + 'and BOI.SSN=' + convert(varchar, @SSN)
if(@BuyerEmail<>'')
set @query= @query + 'and BUD.EmailId=''' + @BuyerEmail + ''''

if isdate(@OpeningDate)=1
set @query=@query + ' and CONVERT(CHAR(10),AUC.StartDate,101)=''' + CONVERT(CHAR(10),@OpeningDate,101) + '''' if isdate(@ClosingDate)=1
set @query=@query + ' and CONVERT(CHAR(10),AUC.EndDate,101)=''' + CONVERT(CHAR(10),@ClosingDate,101) + ''''
if(@LoanTerm > 0)
set @query= @query + 'and MLT.NoOfmonth=' + convert(varchar,@LoanTerm)

if(@MinFicoScore <>'')
set @query= @query + ' and MLT.FicoScore >='+ @MinFicoScore
if(@MaxFicoScore <>'')
set @query= @query + ' and MLT.FicoScore <=' + @MaxFicoScore

if (@FiveMinueRule =1)
set @query= @query + 'and AUC.FiveMinuteRule=1'
if (@FiveMinueRule =0)
set @query= @query + 'and (AUC.FiveMinuteRule=0 or AUC.FiveMinuteRule is null)'


if (@PropertyValue>0)
set @query= @query + 'and PRI.OriginalCost <=' + convert(varchar,@PropertyValue)
if(@ResidenceStatus >0)
set @query= @query + 'and PRI.PropertyUseID=' + convert(varchar,@ResidenceStatus)
if(@LoanPurpose >0)
set @query= @query + 'and PRI.LoanPurposeID=' + convert(varchar,@LoanPurpose)
if(@LoanAmount>0)
set @query= @query + 'and MLT.LoanAmount <=' + convert(varchar,@LoanAmount)
if(@StartingBid<>'')
set @query= @query + 'and BLP.OpeningBid=''' + @StartingBid + ''''
if(@CurrentBid<>'')
set @query= @query + 'and (select min(bid) from auction where loanrequestid=AUC.LoanRequestId) =''' + @CurrentBid + ''''
if @totalbids<>-1
set @query=@query + ' and (select count(bid) from auction where loanrequestid=AUC.LoanRequestId and bid is not null) = ' + CONVERT(varchar,@TotalBids)
if @BidTimes<>''
set @query=@query + ' and (select CONVERT(CHAR(5),max(bidsubmitdate),108) from auction where loanrequestid=AUC.LoanRequestId and bid is not null) = ''' + dbo.AddTimetToBidTime(@BidTimes) + ''''

Exec(@query)

End



Enjoy...
Sanjeev Chauhan
HelpOnDesk Team