Tuesday, October 13, 2009

 

Open New Window in ASP.NET web page using JavaScript

Collected Article from:


http://dotnetspidor.blogspot.com/2009/01/open-new-window-in-aspnet-web-page_28.html



I have found much tricks in different tutorials and forums on opening new window in asp.net web page, using JavaScript, jquery etc. Here I have put most useful of ways to open new window (and pop-up window) in asp.net web page. I hope these tricks will be helpful.
1. Open New Window from HyperLink control

asp:hyperlink id="hyperlink1" runat="server" navigateurl="~/Default.aspx" target="_blank">/asp:HyperLink

Clicking this hyperlink will open the Default.aspx page in new window. In most of the cases this simple coding can save need of lots of JavaScript code!
2. Open New Window on Button Click


asp:button id="btnClck" runat="server" onclick="btnClick_Click"

protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
{
string url = "MyNewPage.aspx?ID=1&cat=test";
string fullURL = "window.open('" + url + "', '_blank', 'height=500,width=800,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
btnClck.Attributes.Add("OnClick", fullURL);
}
}

article from MSDN

http://msdn.microsoft.com/en-us/library/ms536651(VS.85).aspx#Mtps_DropDownFilterText



GL Page and Pax page previews using javascript pop ups




Live Search






Tuesday, October 6, 2009

 

Watermark and Add Copyright Info to your Images on your Local drive using C# and VB.NET

collected from http://www.dotnetcurry.com/ShowArticle.aspx?ID=243&AspxAutoDetectCookieSupport=1


Prevention is better than cure! Most of us, who run websites/blogs or host technical content, face issues of our images being copied and displayed on other blogs. There are a couple of techniques we can adopt to safeguard our copyrighted content and prevent people from doing so. One of them is watermarking our images with our logo or watermarking the website name on the images. A few weeks ago, I had discussed one such technique using ASP.NET. In this article, I will propose a desktop solution using Windows Forms, which can be used to watermark images before you upload the images to the site. This desktop solution basically saves us some processing and response time while watermarking images. Let us get started.
Create a Windows application. Drop a Button control (btnWatermark), a label(lblStatus) and a FolderBrowserDialog component from the ToolBox to the Form.
In the button click, open a dialog box using the FolderBrowerDialog component, which enables the user to select a folder containing images. We then loop through all images in that folder, create a filestream object and then pass it to the AddWatermark(). The AddWatermark method has been taken from a code sample posted by Rong-Chun over here
The AddWatermark accepts a FileStream and then draws the watermark on the image using the Graphics class. Here’s the code to do draw watermark on your images.


C#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;

namespace WatermarkImages
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.folderBrowserDialog1.Description =
"Select the images directory";

// Disallow creation of new files using the FolderBrowserDialog.
this.folderBrowserDialog1.ShowNewFolderButton = false;
}


private void btnWatermark_Click(object sender, EventArgs e)
{
string path = String.Empty;
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
path = folderBrowserDialog1.SelectedPath;
}

if (path == String.Empty)
{
lblStatus.Text = "Invalid directory..";
return;
}


lblStatus.Text = String.Empty;
Image img = null;
string fullPath = String.Empty;

try
{
string[] imgExtension = { "*.jpg", "*.jpeg", ".gif", "*.bmp" };
List files = new List();

DirectoryInfo dir = new DirectoryInfo(path);

foreach (string ext in imgExtension)
{
FileInfo[] folder = dir.GetFiles(ext, SearchOption.AllDirectories);
foreach (FileInfo file in folder)
{
FileStream fs = file.OpenRead();
fullPath = path + @"\" + file.Name ;

Stream outputStream = new MemoryStream();
AddWatermark(fs, "www.dotnetcurry.com", outputStream);
fs.Close();
file.Delete();
img = Image.FromStream(outputStream);

using (Bitmap savingImage = new Bitmap(img.Width, img.Height, img.PixelFormat))
{
using (Graphics g = Graphics.FromImage(savingImage))
g.DrawImage(img, new Point(0, 0));
savingImage.Save(fullPath, ImageFormat.Jpeg);

}

img.Dispose();

}
}
lblStatus.Text = "Processing Completed";
}
catch (Exception ex)
{
lblStatus.Text = "There was an error during processing..";
}
finally
{
if (img != null)
img.Dispose();
}
}


public void AddWatermark(FileStream fs, string watermarkText, Stream outputStream)
{
Image img = Image.FromStream(fs);
Font font = new Font("Verdana", 16, FontStyle.Bold, GraphicsUnit.Pixel);
//Adds a transparent watermark with an 100 alpha value.
Color color = Color.FromArgb(100, 0, 0, 0);
//The position where to draw the watermark on the image
Point pt = new Point(10, 30);
SolidBrush sbrush = new SolidBrush(color);

Graphics gr = null;
try
{
gr = Graphics.FromImage(img);
}
catch
{
// http://support.microsoft.com/Default.aspx?id=814675
Image img1 = img;
img = new Bitmap(img.Width, img.Height);
gr = Graphics.FromImage(img);
gr.DrawImage(img1, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
img1.Dispose();
}

gr.DrawString(watermarkText, font, sbrush, pt);
gr.Dispose();

img.Save(outputStream, ImageFormat.Jpeg);
}

}
}

VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Drawing
Imports System.Windows.Forms
Imports System.IO
Imports System.Drawing.Imaging

Namespace WatermarkImages
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
Me.folderBrowserDialog1.Description = "Select the images directory"

' Disallow creation of new files using the FolderBrowserDialog.
Me.folderBrowserDialog1.ShowNewFolderButton = False
End Sub
Private Sub btnWatermark_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim path As String = String.Empty
Dim result As DialogResult = folderBrowserDialog1.ShowDialog()
If result = DialogResult.OK Then
path = folderBrowserDialog1.SelectedPath
End If

If path = String.Empty Then
lblStatus.Text = "Invalid directory.."
Return
End If


lblStatus.Text = String.Empty
Dim img As Image = Nothing
Dim fullPath As String = String.Empty

Try
Dim imgExtension() As String = { "*.jpg", "*.jpeg", ".gif", "*.bmp" }
Dim files As List(Of FileInfo) = New List(Of FileInfo)()

Dim dir As New DirectoryInfo(path)

For Each ext As String In imgExtension
Dim folder() As FileInfo = dir.GetFiles(ext, SearchOption.AllDirectories)
For Each file As FileInfo In folder
Dim fs As FileStream = file.OpenRead()
fullPath = path & "\" & file.Name

Dim outputStream As Stream = New MemoryStream()
AddWatermark(fs, "www.dotnetcurry.com", outputStream)
fs.Close()
file.Delete()
img = Image.FromStream(outputStream)

Using savingImage As New Bitmap(img.Width, img.Height, img.PixelFormat)
Using g As Graphics = Graphics.FromImage(savingImage)
g.DrawImage(img, New Point(0, 0))
End Using
savingImage.Save(fullPath, ImageFormat.Jpeg)

End Using

img.Dispose()

Next file
Next ext
lblStatus.Text = "Processing Completed"
Catch ex As Exception
lblStatus.Text = "There was an error during processing.."
Finally
If img IsNot Nothing Then
img.Dispose()
End If
End Try
End Sub


Public Sub AddWatermark(ByVal fs As FileStream, ByVal watermarkText As String, ByVal outputStream As Stream)
Dim img As Image = Image.FromStream(fs)
Dim font As New Font("Verdana", 16, FontStyle.Bold, GraphicsUnit.Pixel)
'Adds a transparent watermark with an 100 alpha value.
Dim color As Color = Color.FromArgb(100, 0, 0, 0)
'The position where to draw the watermark on the image
Dim pt As New Point(10, 30)
Dim sbrush As New SolidBrush(color)

Dim gr As Graphics = Nothing
Try
gr = Graphics.FromImage(img)
Catch
' http://support.microsoft.com/Default.aspx?id=814675
Dim img1 As Image = img
img = New Bitmap(img.Width, img.Height)
gr = Graphics.FromImage(img)
gr.DrawImage(img1, New Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel)
img1.Dispose()
End Try

gr.DrawString(watermarkText, font, sbrush, pt)
gr.Dispose()

img.Save(outputStream, ImageFormat.Jpeg)
End Sub

End Class
End Namespace

 

Tips for avoiding Spam Filters with System.Net.Mail

Collected From http://www.andreas-kraus.net/blog/tips-for-avoiding-spam-filters-with-systemnetmail/

I recently noticed that automatic mails sent by one of my online shops were flagged as spam when using GMX, GMail or generally mail services which are using SpamAssassin to filter out spam.

Sending out plain text-mails is old and rusty, if you want to deliver pretty mails to your customers you have to use HTML, unfortunately there is no way around it, but how to make sure that those pretty HTML mails actually reach the customer? Spam filters like SpamAssassin treat HTML Mails as potentially dangerous, so you have to use HTML very carefully.

If you do use HTML Mails you have to create two kinds of Bodys, one HTML Mail Body and one PlainText Mail Body. I show you how to do this in C# / ASP.NET 2.0 by using the built-in System.Net.Mail Class after some general advices.

Here are some recommendations for a automatic HTML mails which are being sent out a hundred times per day:

Don’t forget to add Your HTML Text/Code to your HTML-Text-String
Try to stick with 1-3 Images in total. For example your Logo, a header background and a photo of the particular product.
Use HTML Tags with care. Set a good looking font like Arial, create listings, link tags, bold and italic texts and restrict yourself to create a well formed/layouted text, which is most important. Don’t even think about implenting an embed or object tag for including flash videos or anything like that.
SpamAssassin checks a lot of factors and is using a point-system for filtering out spam, here is a little snippet:

1.723 MSGID_FROM_MTA_ID
0.001 HTML_MESSAGE
5.000 BAYES_99
0.177 MIME_HTML_ONLY
1.047 HTML_IMAGE_ONLY_16
0.629 FORGED_OUTLOOK_HTML

The heaviest impact is BAYES_99, if your text sounds spammy, you are spam flagged. If you e.g. sell Viagra you shouldn’t list the product name in your confirmation mail . Another example is MIME_HTML_ONLY, this hits your mail if you only supply HTML Text, without a seperated PlainText. I won’t explain every function in detail here, if you follow this HowTo you likely won’t run into any problems.

Let’s have a look on how to properly send a HTML Mail with the System.Net.Mail Class, in this case it is sending the Mail via Google Apps / GMail:

public void ExecuteHtmlSendMail(string FromAddress, string ToAddress, string BodyText, string Subject)
{
MailMessage mailMsg = new MailMessage();
mailMsg.From = new MailAddress(FromAddress);
mailMsg.To.Add(new MailAddress(ToAddress));
mailMsg.Subject = Subject;
mailMsg.BodyEncoding = System.Text.Encoding.GetEncoding(”utf-8″);

System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString
(System.Text.RegularExpressions.Regex.Replace(BodyText, @”<(.|\n)*?>”, string.Empty), null, “text/plain”);
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(BodyText, null, “text/html”);

mailMsg.AlternateViews.Add(plainView);
mailMsg.AlternateViews.Add(htmlView);

// Smtp configuration
SmtpClient smtp = new SmtpClient();
smtp.Host = “smtp.gmail.com”;

smtp.Credentials = new System.Net.NetworkCredential(”username”, “password”);
smtp.EnableSsl = true;

smtp.Send(mailMsg);
}

What’s important here: Setting the correct Encoding, in my case utf-8. Create a plainView and htmlView of the mail message. For the plainView I used a simple Regex statement for stripping out the HTML Tags. Add the plainView and htmlView to the AlternateViews Class of the Mail Message and finally send the mail, in my case via SSL, if you don’t know whether you have an Mailserver with SSL capabilities just ask your provider.

Using this construct you send out your HTML Mails as HTML Mail and Plaintext Mail and SpamAssassin is going to like you for that.

I use gmx.net for testing my mails as they are using a pretty well configured SpamAssassin and you can easily see the spam-flags by checking out the Header of the mail (also possible with GMail and hopefully every other mail application out there). An example of this:

X-GMX-Antispam: 5 (HTML_IMAGE_ONLY_12,HTML_MESSAGE,HTML_MIME_NO_HTML_TAG,MIME_HTML_ONLY)
X-GMX-UID: UNbaLmk4ZDI4zQ9QSmY2gY1xemhmY8Gs

A Spam-Score of 5 (=treated as Spam) and it’s telling me that I didn’t supply a PlainText Version of the Mail, after including that one all errors were gone.

Hope this saves some headaches

 

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for (email address).

have done some reading about this and it seems that most people are able to fix this error by doing the following:

1) Right click on Default SMTP Virtual Server and select properties
2) Select the access tab
3) Click the Relay button
4) Click the Add button
5) Type in your ip address

Tuesday, July 21, 2009

 

ASP.NET AJAX SlideShow Extender - Some Common Tips and Tricks

ASP.NET AJAX SlideShow Extender - Some Common Tips and Tricks

SlideShow is cool extender control that comes with the ASP.NET AJAX control toolkit and can be used to create a Slide show by looping images in a round robin fashion. The images are configured with the SlideShow by using a PageMethod or a webservice. In this article, we will see common tips and tricks while using the SlideShow Extender control. In this article, I assume that you are familiar with the SlideShow Extender. If you want to know more about this control, check the documentation over here.
The Ajax Control Toolkit is a separate download that is built on top of the Microsoft ASP.NET Ajax framework. The toolkit allows you to create extenders and controls to enhance the current ASP.NET server controls.
The toolkit can be downloaded from http://tinyurl.com/ajax-toolkit. Information on how to install the toolkit can be found at http://tinyurl.com/toolkit-info. Let us get started.
How to create a Slide Show with images kept on your local disk using the ASP.NET AJAX SlideShow Extender
Here’s a simple demonstration of creating a Slide Show with the images on your disk, using the ASP.NET AJAX SlideShow Extender. I have created an ASP.NET 3.5 website. Drag and drop the SlideShow Extender from the AJAX Control Toolkit on to the page. Create a folder called ‘images’ in your project and add some images to them. After setting a few properties on the SlideShow, the markup would look similar to the following.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>















Height="400px" Width="400px"
ImageUrl="~/images/Autumn Leaves.jpg" />

BehaviorID="SSBehaviorID"
TargetControlID="img1"
SlideShowServiceMethod="GetSlides"
AutoPlay="true"
ImageDescriptionLabelID="lblDesc"
NextButtonID="btnNext"
PreviousButtonID="btnPrev"
PlayButtonID="btnPlay"
PlayButtonText="Play"
StopButtonText="Stop"
Loop="true" >













As shown in the markup, the SlideShow requires a PageMethod called GetSlides that will be called to supply images. Add the following PageMethod GetSlides() in your Default.aspx.cs or .vb that returns a Slide array to the SlideShow Extender control
C#
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static AjaxControlToolkit.Slide[] GetSlides()
{
AjaxControlToolkit.Slide[] imgSlide = new AjaxControlToolkit.Slide[4];

imgSlide[0] = new AjaxControlToolkit.Slide("images/Autumn Leaves.jpg","Autumn","Autumn Leaves");
imgSlide[1] = new AjaxControlToolkit.Slide("images/Creek.jpg","Creek","Creek");
imgSlide[2] = new AjaxControlToolkit.Slide("images/Desert Landscape.jpg", "Landscape", "Landscape");
imgSlide[3] = new AjaxControlToolkit.Slide("images/Dock.jpg","Dock","Dock");

return (imgSlide);
}
VB.NET
_
Public Shared Function GetSlides() As AjaxControlToolkit.Slide()
Dim imgSlide(3) As AjaxControlToolkit.Slide

imgSlide(0) = New AjaxControlToolkit.Slide("images/Autumn Leaves.jpg","Autumn","Autumn Leaves")
imgSlide(1) = New AjaxControlToolkit.Slide("images/Creek.jpg","Creek","Creek")
imgSlide(2) = New AjaxControlToolkit.Slide("images/Desert Landscape.jpg", "Landscape", "Landscape")
imgSlide(3) = New AjaxControlToolkit.Slide("images/Dock.jpg","Dock","Dock")

Return (imgSlide)
End Function
When you run the application, you can see a Slide Show of the images as shown below.

Smooth and Simple!
How to change the time interval between slides at runtime in the ASP.NET AJAX SlideShow Extender
A simple yet effective way is to use JavaScript.
To do so, first add one textbox(txtInterval) and a HTML button control to the page. On clicking the button, the time value in the textbox will be passed to a JavaScript function called changeSlideTime(). In this function, we will retrieve the behavior id of the SliderExtender and then use the set_interval() method of the timer, to increase or decrease the play duration between two slides.




Add the following JavaScript code in the element of your page. The code uses the set_interval() function of the timer to change the Time Interval in between two slides.

Note: The Time duration is to be supplied in milliseconds. So to create a play duration of 10 seconds between two slides, pass a value of 10000.

How to Skip certain Slides based on a condition in the ASP.NET AJAX SlideShow Extender
In order to skip slides based on a certain condition, use the slideChanging event and specify the slide index to be skipped. Then use the set_cancel(true) to skip the slide as shown below:


How to Fade In Fade Out Images in the ASP.NET AJAX SlideShow Extender.
Raymon Wen demonstrated a way to create animations with images in the SlideShow Extender using AnimationExtenders. Add an AnimationExtender from the AJAX Control Toolbox to the page. Configure the FadeIn FadeOut sequences as shown in the mark up over here:






Height="400px" Width="400px"
ImageUrl="~/images/Autumn Leaves.jpg" />


BehaviorID="SSBehaviorID" TargetControlID="img1"
SlideShowServiceMethod="GetSlides" AutoPlay="true"
ImageDescriptionLabelID="lblDesc" NextButtonID="btnNext"
PreviousButtonID="btnPrev" PlayButtonID="btnPlay"
PlayButtonText="Play" StopButtonText="Stop"
Loop="true" >


TargetControlID="img1">




























Now in the section of the page, add the following JavaScript code to play the animation during the slideChanging event as shown below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>












I hope you enjoyed these tips with the SlideShow Extender control. If you have used any useful hacks or tips with this control, use the comments section to share it with the viewers. I hope you liked the article and I thank you for viewing it.

Labels:


 

Code For Remember Me password Checked

protected void UserLogin(object sender, EventArgs e)------>Button_Click
{
if (Membership.ValidateUser(UserName.Text, PassWord.Text))
{
if (RememberDetailsChecked.Checked)
{
HttpCookie c1, c2;
c1 = new HttpCookie("username");
c2 = new HttpCookie("pasword");
c1.Value = UserName.Text;
c2.Value = PassWord.Text;
c1.Expires = DateTime.Now.AddDays(7);
c2.Expires = DateTime.Now.AddDays(7);
Response.AppendCookie(c1);
Response.AppendCookie(c2);
}
else
{
HttpCookie obj1, obj2;
obj1 = Request.Cookies["username"];
obj2 = Request.Cookies["pasword"];
if (obj1 != null && obj2 != null)
{
obj2.Expires = DateTime.Now.AddDays(-1);
Response.AppendCookie(obj2);
}
}
setCookie(UserName.Text);
}
else
{
LoginErrorLabel.Text = "Enter Valid Details *";
}
}
code in page_load...........
if (!Page.IsPostBack)
{
HttpCookie obj1, obj2;
obj1 = Request.Cookies["username"];
obj2 = Request.Cookies["pasword"];
if (obj1 != null && obj2 != null)
{
if(Membership.ValidateUser(obj1.Value, obj2.Value))
{
UserName.Text = obj1.Value;
PassWord.Attributes.Add("value", obj2.Value);
RememberDetailsChecked.Checked = true;
}
}
}

Labels:


 

Examples of applying custom date/time format strings are shown in the following table.


This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]