Tuesday, May 7, 2013

Generate Select All Checkbox control in C# , ASP.Net

Hi guys, today I faced a scenario where I need to create (auto generate) a Select All CheckBox control by C# code behind at runtime and and insert it to the Ajax Control toolkit TabPanel.

Once user will check the Select All checkbox all the other checkbox within that Tab will get checked without post back of page. For opposing post back and achieving mark as check JavaScript is the best option coming in mind. And hence I choose the same.

I wrote JavaScript Global function which accept Select All CheckBox Control Id and look for the related controls and auto generate the required Id for them.

Generate Select All Checkbox : 2bexpert

For achieving this functionality I have written Below mention code:

C# Code for Generating CheckBox Dynamically (Auto Generate Checkbox):

#region Generate SelectAllCbx

    private void GenerateSelectAllCbx(string cbxId, int index, int width, bool isChecked, AjaxControlToolkit.TabPanel tab)

    {

        CheckBox cbAll = new CheckBox();

        cbAll.Attributes.Add("Value", "All");

        cbAll.ID = cbxId + index.ToString();

        cbAll.Text = "Select All";

        cbAll.Width = Unit.Pixel(width);

        cbAll.Checked = isChecked;

        cbAll.Enabled = !isChecked;

        cbAll.Attributes.Add("onclick", "javascript: SelectAll(this," + index.ToString() + ");");

        tab.Controls.Add(cbAll);

 

    }

    #endregion

Just we need to call this method where we want to insert Select All CheckBox:

GenerateSelectAllCbx("cbEngRating_", 4, 750, false, tabICFRating);

 

Whenever this Method would get called it will Insert a Checkbox (Select All) and handle other automatically for achieving that below is JavaScript Code:

function SelectAll(control_id, x) {

        var chkAll = $(control_id);

        var autoId = control_id.id.substring(0, control_id.id.length - x.toString().length)

        for (var i = 0; i < x; i++) {

            $("#" + autoId + i).attr("Checked", chkAll.prop("checked"));

        }

            }

Here I am passing the Control Id and the Postfix Id to generate auto ID.

That’s it now you are able to select auto generated multiple checkbox and mark them check.




Cheers…

Anand Tiwari….

Thursday, April 25, 2013

A Brand New Blogger Editor in BlogSpot.

Wow a brand New Editor in Blogspot, I love the way Blogspot is giving flexibility to the blooger, by this blog Template Editor we can Edit HTML code very easily unlike in previous days it was a simple text editor but now with Line number and color code for each code it is quit easy to Modify as like .

I love this change, thanks Google I love this Editor , guy’s have a look once, below is the Screen shot for Perusal:

image

I am sure you too goanna like this.

 

Cheers…..

Anand Tiwari

Scroll Content of div tag like page scrolling.

Hi guys today I have faced a requirement where I need to Scroll the content of one div to show all the content in it. Actually we had a Modal Popup which was displaying some sort of information based on link click by the user.

When ever we are going to show another html (web page) in modal popup we are facing this type of challenge as there in modal popup if you are scrolling by mouse the Parent page will get started scrolling. And hence here our JavaScript is helping as to achieve this functionality. 

Lets say you have a div with lots of content (text and images or video) and your modal popup size is small to show them at once so in this case you need to do like below .

Here I have used a html table control for Demo purpose you can as you like just we need is the id of the div control which we are going to scroll. Like here ‘’dvcontainer” .

<table width="175px">
<
tr>
<
td>
<
div style="position: relative; width: 175px; height: 160px;


border: 1px solid black;
overflow: hidden">
<
div id="dvcontainer" style="position: absolute;


width: 170px; left: 0; top: 0">
<!--INSERT CONTENT HERE-->
<p>
Anand Mani Tiwari holds an Engineering degree in


Computer Science from BPUT and
has previously worked at NCPL Inc. and now working


at Orion Systems Integrators
Inc for a Client which is worlds Biggest Auditing


Company KPMG. He is a Software
Engineer and working on different Microsoft


Technologies like ASP.Net, WPF, Silverlight,
WCF... He is a Microsoft Certified Professional.


And recently Passed Microsoft Technology
Specialist Exam in HTML 5 with a Excellent


Score of 920/ 1000.
</p>
<
p>
- <a href="http://www.2bexpert.com/p/about-me.html">


Click here to see his complete profile</a>
</
p>
<!--END CONTENT-->
</div>
</
div>
</
td>
<
td>
<
a href="#" onmouseover="move('dvcontainer',1)"


onmouseout="clearTimeout(move.to)">
<
img alt="Page Up" src="images/up.gif" border="0"></a>
<
div style="height: 145px; display: block;


background: url(images/);">
</
div>
<
a href="#" onmouseover="move('dvcontainer',-1)"


onmouseout="clearTimeout(move.to)">
<
img alt="Page Down" src="images/down.gif" border="0"></a>
</
td>
</
tr>
</
table>


 




After this we need to write the code for Scroll the “dvcontainer” content. So here we go with JavaScript ….



<script type="text/javascript" language="javascript">

function
move(id, spd) {
var obj = document.getElementById(id), max = -obj.offsetHeight +


 obj.parentNode.offsetHeight, top = parseInt(obj.style.top);
if ((spd > 0 && top <= 0) || (spd < 0 && top >= max)) {
obj.style.top = top + spd + "px";
move.to = setTimeout(function () { move(id, spd); }, 20);
}
else {
obj.style.top = (spd > 0 ? 0 : max) + "px";
}
}

</script>



That’s it now you can see the div content is getting scroll on mouse hover of Up and Down image.



Required Images for this demo : up       down



I hope this post has helped you, please comment. Thanks

Generate Thumbnail Image in ASP.Net by C# Class

Hi Guys today I am going to show you how you can generate Thumbnail’s of any selected image dynamically by a C# class. This class is very handy in admin area development, where admin has to upload the images.

By this class you can generate not only Thumbnail but the real resource will also get saved in Servers folder which is handy to show the related big image as well.

We can use this Thumbnail Generator class by just calling the function GenerateThumbNail() and passing the required signatures (Parameters), we need to initiate the class first by Creating the instance first for that below is the code block:

  public Helper hlp { get; set; }

Let say we are having a ASP FileUpload control and ASP Button control to select desired file and send the same to server for making thumbnail of selected image.

Below is the *.aspx code:

<fieldset>
    <legend>Thumbnail Generator</legend>
    <asp:FileUpload ID="flUpload" runat="server" /><asp:Button ID="btnUpload"
            runat="server" Text="Upload" onclick="btnUpload_Click" />
    </fieldset>

it will generate a html page like below:

image

Now our Fileupload control having the Sorce file after selecting Image file from local Server (User Computer).

On Upload Button Click by user below mentioned code required:

protected void btnUpload_Click(object sender, EventArgs e)
   {
       hlp = new Helper();
       hlp.GenerateThumbNail(flUpload.PostedFile, "thumbFile",300);
   }

Below is the required Class for Generating Thumbnail:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;

/// <summary>
/// Summary description for Helper
/// </summary>
public class Helper
{
    public Helper()
    {
        //
        // TODO: Add constructor logic here
        //
    }


    public void GenerateThumbNail(HttpPostedFile srcFile,string thumbNailFolder,int width)
    {
        HttpPostedFile myFile = srcFile;
        string filename = srcFile.FileName;
        int oFileLength = myFile.ContentLength;
        if (oFileLength != 0)
        {
            int i = filename.LastIndexOf("\\");
            filename = filename.Substring(i + 1);
            filename = DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + filename;
            string thumb_filename = "thumb_"+DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + filename;
            byte[] myData = new Byte[oFileLength];
            myFile.InputStream.Read(myData, 0, oFileLength);

            System.IO.FileStream newFile
                = new System.IO.FileStream(HttpContext.Current.Server.MapPath("~/images/") + filename,
                                           System.IO.FileMode.Create);
            newFile.Write(myData, 0, myData.Length);
            newFile.Close();

 

            System.Drawing.Image image =
               System.Drawing.Image.FromFile(newFile.Name);
            int srcWidth = image.Width;
            int srcHeight = image.Height;
            int thumbWidth = width;
            int thumbHeight;
            Bitmap bmp;
            if (srcHeight > srcWidth)
            {
                thumbHeight = (srcHeight / srcWidth) * thumbWidth;
                bmp = new Bitmap(thumbWidth, thumbHeight);
            }
            else
            {
                thumbHeight = thumbWidth;
                thumbWidth = (srcWidth / srcHeight) * thumbHeight;
                bmp = new Bitmap(thumbWidth, thumbHeight);
            }

            System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            System.Drawing.Rectangle rectDestination =
                   new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
            gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
            bmp.Save(HttpContext.Current.Server.MapPath("~/"+thumbNailFolder + "/" + thumb_filename));
            bmp.Dispose();
            image.Dispose();
       
        }
    }
}

And that’s it, now be sure to make two folders in you solution (Project). One for original Picture Upload and another one for Thumbnail file.

I am pasting Overall screen shot of Project which will help you :

image

 

Cheers…..

 

Regards,

Anand Tiwari

Sunday, November 20, 2011

What is Application Library Caching

Most of the time including this extra assembly in your XAP file would be fine. There is an alternative though. You can separated the Microsoft.Maps.MapControl assembly out and have the client’s browser cache it locally. This is called “Application Library Caching”. If the client already has a cached copy of the assembly it does not need to be downloaded again. This would obviously decrease the amount of content that needs to be downloaded for the application to run. To configure the Silverlight project to use library caching you right-click on the project in Solution Explorer and choose the “Properties” option. This will open the properties tab for the project and then you check the box labeled “Reduce XAP size by using application library caching”, as shown in the following screen capture:

ClientBin folder is used to place the .XAP file of Silverlight application. You can keep this anywhere in your web application but this is the default that is used by the Silverlight.
The .XAP mime type is: application/x-silverlight

AppManifest.xaml file?

The AppManifest.xml file defines the assemblies that get deployed in the client application. This file is automatically updated when compiling your application.
Basic example:

<deployment entrypointassembly="MySimpleSilverlight" entrypointtype="MySimpleSilverlight.App" runtimeversion="3.0.40624.0" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/client/2007/deployment">
<deployment.parts>
<assemblypart source=" MySimpleSilverlight.dll" x:name="MySimpleSilverlight">
<assemblypart source="Microsoft.Maps.MapControl.Common.dll" x:name="Microsoft.Maps.MapControl.Common">
<assemblypart source="Microsoft.Maps.MapControl.dll" x:name="Microsoft.Maps.MapControl">
</assemblypart></assemblypart></assemblypart></deployment.parts>
</deployment>
Based on the settings of a referenced assembly it is added to the Application manifest. For example, if you have an assembly that you are referencing in your application but do not wish to have it included into the. XAP file you can choose to set “Copy Local” to false. See the image below:

In this example I’m referencing the Microsoft.Maps.MapControl.Common assembly and chose not to have a local copied deployed with the .XAP. I’ll then need to add “on demand download of the assembly” when accessing it in my code.
This can be useful to have only your base assembly deployed and have an on demand download of subsequent assemblies on the fly so that your initial download time is minimal. When only a part of your application uses a specific assembly you may want to use this mechanism.

What is XAP File?

A XAP file (pronounced "zap") is basically a compressed output file for the Silverlight application containing Silverlight solution components such as the compiled XAML and code-behind, an application manifest and possibly one or more assemblies delivering Silverlight controls.
When a Silverlight project is built in Visual Studio all of the files, XAML and .NET code, are compiled into a single DLL.  This DLL file is then compressed into a zip file that gets named with a .XAP extension rather than the traditional .ZIP.  In addition to XAML and code files, graphics and media files are compiled by default into the DLL assembly as well.
".XAP" files use the standard .zip compression algorithm to minimize client download size. A "hello world" .NET Silverlight application (built using VB or C#) is about 5KB in size. The size of the file depends on the XAML files, assemblies used in Silverlight project.

To view the contents of a .XAP file you can rename the extension of the .XAP file to .ZIP. Then view the .ZIP file using any standard .ZIP utility.


A basic XAP file will have an assembly related to specific code for the application, an application manifest file and any additional assemblies need to run the application. At a minimum, two files are needed, the application manifest file and the application assembly.
For example:
  • AppManifest.xaml
  • Demo1.dll
Here Microsoft.Maps.MapControl.Common.dll and Microsoft.Maps.MapControl.dll are two external dlls used in the Silverlight application to show the Bing Map.External resources like images or other types of files can also be added to the .XAP file if you do embed them into your client DLL .

Monday, December 27, 2010

What is Index?

An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes; they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when there is no index available to help a query. In a table scan SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance.

What is View?

A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views.

What is Trigger?

A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures.

Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger.

What is Stored Procedure?

A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.

e.g. sp_helpdb, sp_renamedb, sp_depends etc.

List All Tables of Database


USE YourDBName
GO
SELECT *
FROM sys.Tables
GO

Monday, December 6, 2010

How to Add CSS dynamically to controls in C#, ASP.NET

To add style Dynamically just add this code snippet.
Control_ID.Style.Add("color","#FFFF99");
As in the above example I had just given a example to change the font color dynamically. You can use another method to add the style to the control dynamically... Like
Control_ID.Attribute.Add("Style='color:#FFFF99;'");

How to Encrypt and Decrypt the Query string automatically by C#, Asp.Net

Just Create a Businesslogic class in App_code folder with the name QueryStringModule.cs
and then add the below given code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// 
/// Summary description for QueryStringModule
/// 
public class QueryStringModule : IHttpModule
{
    ///   
    /// Summary description for QueryStringModule  
    ///   
    
        //  private ILog m_Logger = LogManager.GetLogger(typeof(QueryStringModule));  
        #region IHttpModule Members

        public void Dispose()
        {
            // Nothing to dispose  
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        #endregion

        private const string PARAMETER_NAME = "enc=";
        private const string ENCRYPTION_KEY = "key";

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            string query = string.Empty;
            string path = string.Empty;

            try
            {
                if (context.Request.Url.OriginalString.Contains("aspx") && context.Request.RawUrl.Contains("?"))
                {
                    query = ExtractQuery(context.Request.RawUrl);
                    path = GetVirtualPath();

                    if (query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase))
                    {
                        // Decrypts the query string and rewrites the path.  
                        string rawQuery = query.Replace(PARAMETER_NAME, string.Empty);
                        string decryptedQuery = Decrypt(rawQuery);
                        context.RewritePath(path, string.Empty, decryptedQuery);
                    }
                    else if (context.Request.HttpMethod == "GET")
                    {
                        // Encrypt the query string and redirects to the encrypted URL.  
                        // Remove if you don't want all query strings to be encrypted automatically.  
                        string encryptedQuery = Encrypt(query);
                        context.Response.Redirect(path + encryptedQuery, false);
                    }
                }
            }
            catch (Exception ex)
            {
                // m_Logger.Error("An error occurred while parsing the query string in the URL: " + path, ex);  
                context.Response.Redirect("~/Home.aspx");
            }

        }

        ///   
        /// Parses the current URL and extracts the virtual path without query string.  
        ///   
        /// The virtual path of the current URL.  
        private static string GetVirtualPath()
        {
            string path = HttpContext.Current.Request.RawUrl;
            path = path.Substring(0, path.IndexOf("?"));
            path = path.Substring(path.LastIndexOf("/") + 1);
            return path;
        }

        ///   
        /// Parses a URL and returns the query string.  
        ///   
        /// The URL to parse./// The query string without the question mark.  
        private static string ExtractQuery(string url)
        {
            int index = url.IndexOf("?") + 1;
            return url.Substring(index);
        }

        #region Encryption/decryption

        ///   
        /// The salt value used to strengthen the encryption.  
        ///   
        private readonly static byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());

        ///   
        /// Encrypts any string using the Rijndael algorithm.  
        ///   
        /// The string to encrypt./// A Base64 encrypted string.  
        private static string Encrypt(string inputText)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            byte[] plainText = Encoding.Unicode.GetBytes(inputText);
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

            using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainText, 0, plainText.Length);
                        cryptoStream.FlushFinalBlock();
                        return "?" + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());
                    }
                }
            }
        }

        ///   
        /// Decrypts a previously encrypted string.  
        ///   
        /// The encrypted string to decrypt./// A decrypted string.  
        private static string Decrypt(string inputText)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            byte[] encryptedData = Convert.FromBase64String(inputText);
            PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

            using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
            {
                using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        byte[] plainText = new byte[encryptedData.Length];
                        int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                        return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                    }
                }
            }
        }

        #endregion

    }


After then in web.config file add this code...

 


Thats it, now get the Querystring on any page in encripted manner,
For example:
LblQuery.Text=Request.QueryString["id"].ToString();

Friday, December 3, 2010

Disable Right Click to secure your webpage by JavaScript, ASP.Net

 


Searching All columns in one table one by one for a particular data in SQL Server

SELECT 
        * 
FROM 
        testview
WHERE 
        Username like '%' + @search + '%' 
OR 
        Description like '%' + @search + '%' 
OR  
        Title like '%' + @search + '%'

How to add two different columns data in one columns from SQL server and C#

By using LTRIM();

string commnd = "select id,(LTRIM(FirstName)+' '+Ltrim(LastName)) as [Name],Date_of_Birth,Email_id,Phone_no,Postal_Address,imgURL from Candidate_Info where id=" + id;

Thats all...

How to make corp and thumbnail of any size of image in C#, ASP.NET

With out loosing clarity of the image you can get it by given two method, In my case I had to upload the image in the server and show them in the gallery...

protected void btnUpload_Click(object sender, EventArgs e)
{
// Initialize variables
string sSavePath;
string sThumbExtension;
int intThumbWidth;
int intThumbHeight;

// Set constant values

sSavePath = "uploadedImages/";
sThumbExtension = "_thumb";
intThumbWidth = 160;
intThumbHeight = 120;

// If file field is not empty

if (fileUploader.PostedFile != null)
{
// Check file size (must not be 0)

HttpPostedFile myFile = fileUploader.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
lblOutput.Visible = true;
lblOutput.Text = "No file was uploaded.";
return;
}

// Check file extension (must be JPG)

if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
lblOutput.Visible = true;
lblOutput.Text = "The file must have an extension of JPG";
return;
}

// Read file into a data stream

byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);

// Make sure a duplicate file does not exist.  If it does, keep on appending an 

// incremental numeric until it is unique

string sFilename = System.IO.Path.GetFileName(myFile.FileName);

int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}

// Save the stream to disk

System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();

// Check whether the file is really a JPEG by opening it

System.Drawing.Image.GetThumbnailImageAbort myCallBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap;
try
{
myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));

// If jpg file is a jpeg, create a thumbnail filename that is unique.

file_append = 0;
string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ sThumbExtension + ".jpg";
while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
{
file_append++;
sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
file_append.ToString() + sThumbExtension + ".jpg";
}

// Save thumbnail and output it onto the webpage

System.Drawing.Image myThumbnail
= myBitmap.GetThumbnailImage(intThumbWidth,
intThumbHeight, myCallBack, IntPtr.Zero);
myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile));
filename = sThumbFile;
imgUser.ImageUrl = sSavePath + sThumbFile;
fileURL = sSavePath + sThumbFile;
// Displaying success information
lblOutput.Visible = true;
lblOutput.Text = "File uploaded successfully!";

// Destroy objects

myThumbnail.Dispose();
myBitmap.Dispose();
}
catch (ArgumentException errArgument)
{
// The file wasn't a valid jpg file
lblOutput.Visible = true;
lblOutput.Text = "The file wasn't a valid jpg file.";
System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
}
}

}

Next...

public bool ThumbnailCallback()
{
return false;
}

Thats all...

Friday, November 26, 2010

How to Read and Get Data From XML Document in C#

By this Method we can easily get Data from XML Database. For this first of all create a "ContactsList.xml" XML file and under root section add your recoreds.

public void GetData()
{
try
{
string path = "ContactsList.xml";
FileStream fs = new FileStream path,FileMode.Open,FileAccess.Read, FileShare.ReadWrite);
DataSet ds = new DataSet();
ds.ReadXml(fs);
if (ds.Tables.Count != 0)
{
DataTable dt = ds.Tables[0];

int a = dt.Rows.Count;

for (int i = 0; i < a; i++)
{
string[] str1 = new string[4];
str1[0] = dt.Rows[i].ItemArray[0].ToString();


str1[1] = dt.Rows[i].ItemArray[1].ToString();
str1[2] = dt.Rows[i].ItemArray[2].ToString();
int count = Convert.ToInt32(dt.Rows[i].ItemArray[7].ToString());
if (count.Equals(1) || count.Equals(0))
{
str1[3] = dt.Rows[i].ItemArray[3].ToString();
ListViewItem item1 = new ListViewItem(str1);
ldtvw_Contact.Items.Add(item1);
}
else
{
string interests = dt.Rows[i].ItemArray[3].ToString() + "," + dt.Rows[i].ItemArray[4].ToString() + "," + dt.Rows[i].ItemArray[5].ToString() + "," + dt.Rows[i].ItemArray[6].ToString();
str1[3] = interests;
ListViewItem item1 = new ListViewItem(str1);
ldtvw_Contact.Items.Add(item1);
}

}

fs.Close();
}

Thats All....

Thursday, November 25, 2010

How to Generate Random String in C#, ASP.NET

To Generate a Random String is very Tricky and useful stuff to Know as we can use this functionality at the time of Generating Random Password automatically for each User Registering on the website.

I am sure this will help you a lot, here I am writing the Method to Generate the Random String.

private string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    }
Now the above code will generate the Random String. If you want to have a Strong Password then password must contains Number. So lets go to generate Random Numbers:
public string GetRandomNumber()
    {
        StringBuilder strbuild = new StringBuilder();
        strbuild.Append(RandomNumber(1000, 9999));
        return strbuild.ToString();
    }

private int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }

Now you are ready to generate a random password. for that you have to call these methods as given below:
public string GetPassword()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(RandomString(4, true));
        builder.Append(RandomNumber(1000, 9999));
        builder.Append(RandomString(2, false));
        return builder.ToString();
    }

That's All, Please give your comments if the post is helpful.