Thursday, January 31, 2008

Send a huge range of email (bulk)

if (e.CommandName == "Send")
{
DataSet _dsSubscribersList = new DataSet();
_dsSubscribersList = _objNL.GetSubscribersList();
int count = 0;
if (_dsSubscribersList.Tables.Count > 0 && _dsSubscribersList.Tables[0].Rows.Count > 0)
{
DataSet _dsNewsletter = new DataSet();
_dsNewsletter = _objNL.GetNewsLetterDetailsByNewsletterID(
Convert.ToInt32(e.CommandArgument));
if (_dsNewsletter.Tables.Count > 0 && _dsNewsletter.Tables[0].Rows.Count > 0)
{
try
{
string From = ConfigurationManager.AppSettings["NewslettersSender"].ToString();
string To = null;
string body = HttpUtility.HtmlDecode(_dsNewsletter.Tables[0].Rows[0]["NewsBody"].ToString());
for (int i = 0; i < _dsSubscribersList.Tables[0].Rows.Count; i++)
{
To = (
string)_dsSubscribersList.Tables[0].Rows[i]["Email"];
body = body.Replace("[Subscriber Name]", To);
body = body.Replace(
"[userid]", _dsSubscribersList.Tables[0].Rows[0]["ID"].ToString());
try
{
//System.Threading.Thread.Sleep(4000);
SendMail(To, From, (string)_dsNewsletter.Tables[0].Rows[0]["Subject"], body);
count++;
}
catch
{
count--;
}
}
}
catch //(Exception ex)
{
lblMsg1.Text =
"Sending newsletting failure. Please try again.";//ex.Message +"sri 1"; //
lblMsg1.ForeColor = Color.Red;
return;
}
int x = 0;
x = _objNL.Newsletters_SetHasSent(
Convert.ToInt32(e.CommandArgument));
if (x == 1)
{
BindNewsLetters();
lblMsg1.Text =
"Newsletter send successfully to " + count + " subscribers. ";
dvRepeaters.Style.Value =
"display:block";
dvProgress.Style.Value =
"display:none";
}
}
else
{
lblMsg1.Text = "No newsletters to send!!";
}
}
else
{
lblMsg1.Text =
"No subscriber to send newsletter!!";
}
}

-----------------------------------------------------------------------------------------
//send email

private void SendMail(string To, string From, string Subject, string body)
{
MailMessage _mm = new MailMessage(From, To, Subject, body);
_mm.IsBodyHtml =
true;
SmtpClient _sc = new SmtpClient();
_sc.Send(_mm);
}

Thursday, January 24, 2008

calculating users online

Membership.GetNumberOfUsersOnline()

Wednesday, January 23, 2008

Page Log Image & JavaScript Page Processing

We have provided below sample source code for JavaScript Page Processing in Asp.Net. You can copy and paste it in your pages to create the sample application.
Code for Processing Page (PageProcessor.aspx)



scrip
function PageOnLoad()
{
location.href = "<%=PageToLoad%>";
document.images['imgsrc'].src="Images/Loading.gif";
}
script


body bottommargin="0" leftmargin="0" rightmargin="0" topmargin="0" onload="PageOnLoad();"
form id="form1" runat="server"
div
table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%"
tr
td height="50" class="NormalText" align=center valign="bottom"
h3We are processing your request. Please wait.. h3
td
tr
tr
td align="center" height="250" valign="top
img src="" name="imgsrc" td
tr
tab le
di v




Source Code of code-behind file (PageProcessor.aspx.cs)

protected string PageToLoad;

protected void Page_Load(object sender, EventArgs e)
{
PageToLoad = Request.QueryString["PageId"];
}

First paragraph of data from sql server

SELECT ID, Body, CHARINDEX(CHAR(13), Body) AS FirstParagraphLen FROM MyTable


or

SELECT ID,SUBSTRING(Body, 1, CHARINDEX(CHAR(13), Body)) AS 'Text'
FROM TableName

Tuesday, January 22, 2008

How to access Cookies from Other web pages

 Public Sub DisplayCookies()

'Create a WebRequest to the specified URI.
Dim req As HttpWebRequest = CType(WebRequest.Create("http://werweb.com/whoison.php"), HttpWebRequest)

'Get an empty cookie container.
req.CookieContainer = New CookieContainer

'Send the request and return the response.
Dim resp As HttpWebResponse = CType(req.GetResponse(), HttpWebResponse)

'Display the cookies.
Dim alertStr As String
alertStr = "Number of Cookies: " & resp.Cookies.Count.ToString() & Environment.NewLine()
alertStr = alertStr & "------------------------------" & Environment.NewLine()

Dim i As Integer
For i = 0 To resp.Cookies.Count - 1
alertStr = alertStr & resp.Cookies(i).Name & "=" & resp.Cookies(i).Value & Environment.NewLine()
Next
MessageBox.Show(alertStr)

'Close the Response.
resp.Close()
End Sub

Create Thumbnail of an image

System.Drawing.Image image = System.Drawing.Image.FromFile("c:\\mypic.jpg");
System.Drawing.Image.GetThumbnailImageAbort tnabort = new System.Drawing.Image.GetThumbnailImageAbort(tnCallback);
System.Drawing.Image tnimage = image.GetThumbnailImage(32, 32, tnabort, IntPtr.Zero);
tnimage.Save("c:\\tnmypic.jpg");

public bool tnCallback()
{
return true;
}

Send Web Page as Email

//Function which convert URL information as string
//Which is used latter to passed as body message.
private String readHtmlPage(string url)
{
String result;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
objResponse = objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()) )
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}


//Code for sending webpage as email.
private void btnSend_Click(object sender, System.EventArgs e)
{
//URL is converted into string message.
String message=readHtmlPage(txtURL.Text);
String mailServer = "192.168.0.10"; //Change with your mail server address.


try
{
MailMessage Mailer = new MailMessage();
Mailer.From = txtFrom.Text;
Mailer.To = txtTo.Text;
Mailer.Subject = txtSubject.Text;
Mailer.Body = message;
Mailer.BodyFormat = System.Web.Mail.MailFormat.Html;
SmtpMail.Server(mailServer);
SmtpMail.Send(Mailer);
lblResult.Text = "Page successfully sent!";
}
catch(Exception ex)
{
lblResult.Text = "An error occurred: " + ex.ToString();
}

}

Random data from database

select * from employees order by NEWID()

Programmatically embed a picture inside an Excel Sheet

he following code uses EXCEL automation to open an existing workbook and embed an image.

In order to run this code, please add a COM reference to Microsoft Excel 11.0 Object Library in your project


object missingParam = Type.Missing;
ApplicationClass objExcel = new ApplicationClass();
Workbook workbook = objExcel.Workbooks.Open(@"c:\book1.xls", missingParam, missingParam, missingParam, missingParam,
missingParam, missingParam, missingParam, missingParam,
missingParam, missingParam, missingParam, missingParam,
missingParam, missingParam);
Worksheet worksheet = (Worksheet) workbook.Worksheets["Sheet1"];
Range cellRange = worksheet.get_Range("A2", "A2");
string picFilePath = @"d:\sailboat.jpg";
Image picObject = Image.FromFile(picFilePath);
System.Windows.Forms.Clipboard.SetDataObject(picObject, true);
worksheet.Paste(cellRange, picObject);
workbook.Save();
System.Windows.Forms.Clipboard.Clear();
objExcel.Quit();

Exporting the DataGrid to a Word file

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack)
{
SqlConnection conn = new SqlConnection ("data source=(local);initial catalog=Northwind;Pwd=xxxxxx;User ID=sa");
SqlCommand cmd = new SqlCommand ("Select LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address, City, Region, PostalCode, Country from Employees", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
myDataGrid.DataSource = ds.Tables[0];
myDataGrid.DataBind();
}

}

private void Button2_Click(object sender, System.EventArgs e)
{
// export to word
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");

Response.Charset = "";

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ContentType = "application/vnd.word";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

myDataGrid.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();

}

Text to Speech Applications in C#


Microsoft always provides simple solutions for complex problems.

Microsoft introduced Speech SDK 5.1 to handle text to speech applications. You can download speech SDK from below microsoft Site.

http://www.microsoft.com/downloads/details.aspx?FamilyId=5E86EC97-40A7-453F-B0EE-6583171B4530&displaylang=en

After installed SpeechSDK51.exe, you need to do the following steps to create speech application.

1. Open new C# Web Application.
2. Add the Reference Microsoft object speech application
3. Add the namespace : using SpeechLib;
4. You should refer the below api for this application.

[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

Find the simple source code for speech application in web.

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 Microsoft.VisualBasic.Devices;
using Microsoft.VisualBasic;
using System.Runtime.InteropServices;
using SpeechLib;

public partial class _Default : System.Web.UI.Page
{
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

protected void Button4_Click(object sender, EventArgs e)
{
SpVoice spVoice = new SpVoice();
SpeechVoiceSpeakFlags svsp = new SpeechVoiceSpeakFlags();
spVoice.Speak(this.TextBox1.Text.ToString(),svsp);
}
}

Record Voice From Microphone

        
1. Open C#.net web applications. And added the blow namespace.

using Microsoft.VisualBasic.Devices;
using Microsoft.VisualBasic;
using System.Runtime.InteropServices;

2. Add the below API.
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

3. Create three Buttons and given the below name and text for the buttons.

1. Record
2. SaveStop
3. Read

1. Under Record Button Click paste the below Code:

// record from microphone
mciSendString("open new Type waveaudio Alias recsound", "", 0, 0);
mciSendString("record recsound", "", 0, 0);

2. Under Save / Stop button Click,


// stop and save
mciSendString("save recsound c:\\record.wav", "", 0, 0);
mciSendString("close recsound ", "", 0, 0);
Computer c = new Computer();
c.Audio.Stop();

3. Under Read Button Click

Computer computer = new Computer();
computer.Audio.Play("c:\\record.wav", AudioPlayMode.Background);


Save and Execute it.

Monday, January 21, 2008

Read RSS Feeds and display in ASP.NET data grid

private void Page_Load(object sender, System.EventArgs e)
{
DataSet ds=new DataSet();
ds.ReadXml("http://www.dotnetbips.com/articles/rssfeed.aspx");
dgRSS.DataSource=ds.Tables[2].DefaultView;
dgRSS.DataBind();
}


private void dgRSS_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
dgRSS.CurrentPageIndex=e.NewPageIndex;
dgRSS.DataBind();
}