RSS

Category Archives: ASP Dot Net C#

Create C# classes From MySQL table


If you use MySQL database & you need to generate C# Property Class then you use this Stored Procedure which helpful for you.

DELIMITER $$

DROP PROCEDURE IF EXISTS Sp_Table_Class_PropertyCPlus$$
CREATE PROCEDURE Sp_Table_Class_PropertyCPlus(IN p_tableschema VARCHAR(50),IN p_tablename VARCHAR(50))
BEGIN
— call Sp_Table_Class_PropertyCPlus (‘mydb’,’lotwisesaleprice’ )
SELECT CONCAT(‘public ‘,tps.dest,’ ‘,column_name,'{get;set;}’) AS CODE
FROM information_schema.columns c
JOIN(
SELECT ‘char’ AS orign ,’string’ AS dest UNION ALL
SELECT ‘varchar’ ,’string’ UNION ALL
SELECT ‘longtext’ ,’string’ UNION ALL
SELECT ‘datetime’ ,’DateTime’ UNION ALL
SELECT ‘text’ ,’string’ UNION ALL
SELECT ‘bit’ ,’int’ UNION ALL
SELECT ‘bigint’ ,’int’ UNION ALL
SELECT ‘int’ ,’int’ UNION ALL
SELECT ‘double’ ,’double’ UNION ALL
SELECT ‘decimal’ ,’double’ UNION ALL
SELECT ‘date’ ,’DateTime’ UNION ALL
SELECT ‘tinyint’ ,’bool’
) tps ON c.data_type LIKE tps.orign
WHERE
table_schema=p_tableschema AND

table_name=p_tablename
ORDER BY c.ordinal_position;
END$$

DELIMITER ;

Another Way to Generate BLL Class

DELIMITER $$
DROP PROCEDURE IF EXISTS Sp_Table_Class_GenCSharpModel$$
CREATE PROCEDURE Sp_Table_Class_GenCSharpModel(IN pTableName VARCHAR(255) )
BEGIN

— call Sp_Table_Class_GenCSharpModel(‘lotwisesaleprice’)
DECLARE vClassName VARCHAR(255);
DECLARE vClassCode MEDIUMTEXT;
DECLARE v_codeChunk VARCHAR(1024);
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE code_cursor CURSOR FOR
SELECT CODE FROM temp1;

DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;

SET vClassCode =”;
/* Make class name*/
SELECT (CASE WHEN col1 = col2 THEN col1 ELSE CONCAT(col1,col2) END) INTO vClassName
FROM(
SELECT CONCAT(UCASE(MID(ColumnName1,1,1)),LCASE(MID(ColumnName1,2))) AS col1,
CONCAT(UCASE(MID(ColumnName2,1,1)),LCASE(MID(ColumnName2,2))) AS col2
FROM
(SELECT SUBSTRING_INDEX(pTableName, ‘‘, -1) AS ColumnName2, SUBSTRING_INDEX(pTableName, ‘‘, 1) AS ColumnName1) A) B;

/*store all properties into temp table*/
CREATE TEMPORARY TABLE IF NOT EXISTS  temp1 ENGINE=MYISAM  
AS (
SELECT CONCAT( 'public ', ColumnType , ' ' , FieldName,' { get; set; }') CODE
FROM(
SELECT (CASE WHEN col1 = col2 THEN col1 ELSE CONCAT(col1,col2)  END) AS FieldName, 
CASE DATA_TYPE 
        WHEN 'bigint' THEN 'long'
        WHEN 'binary' THEN 'byte[]'
        WHEN 'bit' THEN 'bool'
        WHEN 'char' THEN 'string'
        WHEN 'date' THEN 'DateTime'
        WHEN 'datetime' THEN 'DateTime'
        WHEN 'datetime2' THEN 'DateTime'
        WHEN 'datetimeoffset' THEN 'DateTimeOffset'
        WHEN 'decimal' THEN 'decimal'
        WHEN 'float' THEN 'float'
        WHEN 'image' THEN 'byte[]'
        WHEN 'int' THEN 'int'
        WHEN 'money' THEN 'decimal'
        WHEN 'nchar' THEN 'char'
        WHEN 'ntext' THEN 'string'
        WHEN 'numeric' THEN 'decimal'
        WHEN 'nvarchar' THEN 'string'
        WHEN 'real' THEN 'double'
        WHEN 'smalldatetime' THEN 'DateTime'
        WHEN 'smallint' THEN 'short'
        WHEN 'mediumint' THEN 'INT'
        WHEN 'smallmoney' THEN 'decimal'
        WHEN 'text' THEN 'string'
        WHEN 'time' THEN 'TimeSpan'
        WHEN 'timestamp' THEN 'DateTime'
        WHEN 'tinyint' THEN 'bool'
        WHEN 'uniqueidentifier' THEN 'Guid'
        WHEN 'varbinary' THEN 'byte[]'
        WHEN 'varchar' THEN 'string'
        WHEN 'year' THEN 'UINT'
         WHEN 'double' THEN 'double'
          WHEN 'decimal' THEN 'decimal'
              WHEN 'longtext' THEN 'string'
        ELSE 'UNKNOWN_' + DATA_TYPE
    END ColumnType
FROM(
SELECT CONCAT(UCASE(MID(ColumnName1,1,1)),LCASE(MID(ColumnName1,2))) AS col1,
CONCAT(UCASE(MID(ColumnName2,1,1)),LCASE(MID(ColumnName2,2))) AS col2, DATA_TYPE
FROM
(SELECT SUBSTRING_INDEX(COLUMN_NAME, '_', -1) AS ColumnName2,
SUBSTRING_INDEX(COLUMN_NAME, '_', 1) AS ColumnName1,
DATA_TYPE, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS  WHERE table_name = pTableName) A) B)C);

SET vClassCode = '';
/* concat all properties*/
OPEN code_cursor;

        get_code: LOOP

            FETCH code_cursor INTO v_codeChunk;

            IF v_finished = 1 THEN
                LEAVE get_code;
            END IF;

            -- build code
            SELECT  CONCAT(vClassCode,'\r\n', v_codeChunk) INTO  vClassCode ;

        END LOOP get_code;

    CLOSE code_cursor;
DROP TABLE temp1;
/make class/
SELECT CONCAT('public class ',vClassName,'\r\n{', vClassCode,'\r\n}');
END

 
Leave a comment

Posted by on November 16, 2020 in ASP Dot Net C#, My SQL

 

Use Currency Format For Different Cultures c#


            double value = 5623345.6789;

            //For Default System Culture

            // By default, single letter C displays currency upto two decimal digits

            Console.WriteLine(value.ToString(“C”, CultureInfo.CurrentCulture));

            // C2 displays currency upto two digits

            Console.WriteLine(value.ToString(“C2”, CultureInfo.CurrentCulture));

            // C3 displays currency upto three digits

            Console.WriteLine(value.ToString(“C3”, CultureInfo.CurrentCulture));

            // C4 displays currency upto four digits

            Console.WriteLine(value.ToString(“C4”, CultureInfo.CurrentCulture));

            // C5 displays currency upto five digits

            Console.WriteLine(value.ToString(“C5”, CultureInfo.CurrentCulture));

            //For Japan Format

            Console.WriteLine(“\n——— Dispalying Currency for Japan —————\n”);

            Console.WriteLine(value.ToString(“C”, CultureInfo.CreateSpecificCulture(“ja-JP”)));

            //For Denmark Format

            Console.WriteLine(“\n——— Dispalying Currency for Denmark —————\n”);

            Console.WriteLine(value.ToString(“C”,       CultureInfo.CreateSpecificCulture(“da-DK”)));

           if Possible same program use with Multiple currencies and you want to fix currency not dependent on Culture then use this

      lblCustomerPayment.Text = string.Format(new CultureInfo(“en-US”, true), “{0:C2}”, value );

For more Help to Explore this below link

https://www.c-sharpcorner.com/UploadFile/0f68f2/converting-a-number-in-currency-format-for-different-culture/

 

 
Leave a comment

Posted by on October 18, 2018 in ASP Dot Net C#, WinForm

 

Encryption/Decryption Function in .NET


 

C#

 

public string Encrypt(string str)
    {
        string EncrptKey = “2013;[pnuLIT)X”;
        byte[] byKey = { };
        byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
        byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }

 public string Decrypt(string str)
    {
        str = str.Replace(” “, “+”);
        string DecryptKey = “2013;[pnuLIT)Y”;
        byte[] byKey = { };
        byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
        byte[] inputByteArray = new byte[str.Length];
        byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        inputByteArray = Convert.FromBase64String(str.Replace(” “, “+”));
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
        return encoding.GetString(ms.ToArray());
    }

 

VB.Net

Public Function Encrypt(str As String) As String
Dim EncrptKey As String = “2013;[pnuLIT)X”
Dim byKey As Byte() = {}
Dim IV As Byte() = {18, 52, 86, 120, 144, 171, _
205, 239}
byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8))
Dim des As New DESCryptoServiceProvider()
Dim inputByteArray As Byte() = Encoding.UTF8.GetBytes(str)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
End Function

 
Public Function Decrypt(str As String) As String
str = str.Replace(” “, “+”)
Dim DecryptKey As String = “2013;[pnuLIT)Y”
Dim byKey As Byte() = {}
Dim IV As Byte() = {18, 52, 86, 120, 144, 171, _
205, 239}
Dim inputByteArray As Byte() = New Byte(str.Length – 1) {}

byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8))
Dim des As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(str.Replace(” “, “+”))
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
End Function

 

 
1 Comment

Posted by on November 22, 2013 in ASP Dot Net C#, Vb.Net

 

Tags: , , ,

ASP.NET Page Life Cycle Events


When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal.

 

In this article, I will discuss in detail the ASP.NET page life cycle Events

 

(1) PreInit 

 

The entry point of the page life cycle is the pre-initialization phase called “PreInit”. This is the only event where programmatic access to master pages and themes is allowed.  You can dynamically set the values of master pages and themes in this event.  You can also dynamically create controls in this event.

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class _Default : System.Web.UI.Page

{

   protected void Page_PreInit(object sender, EventArgs e)

{

     //  Use this event for the following:

        //  Check the IsPostBack property to determine whether this is the first time the page is being processed.

        //  Create or re-create dynamic controls.

        //  Set a master page dynamically.

        //  Set the Theme property dynamically.       

}

 

(2)Init

 

This event fires after each control has been initialized, each control’s UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

 

protected void Page_Init(object sender, EventArgs e)

{

    // Raised after all controls have been initialized and any skin settings have been applied.
    // Use this event to read or initialize control properties.

}

 

(3)InitComplete

 

Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

 

protected void Page_InitComplete(object sender, EventArgs e)

{

    // Raised by the  Page object. Use this event for processing tasks that require all initialization be complete. 

}

 

(4)PreLoad

 

Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance
Loads ViewState : ViewState data are loaded to controls
Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request.
Loads Postback data : postback data are now handed to the page controls
Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control’s unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page.

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

 

protected override void OnPreLoad(EventArgs e)

{

        // Use this event if you need to perform processing on your page or control before the  Load event.

        // Before the Page instance raises this event, it loads view state for itself and all controls, and
        // then processes any postback data included with the Request instance.

}

 

(5)Load

 

The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

 

protected void Page_Load(object sender, EventArgs e)

{

     // The  Page calls the  OnLoad event method on the  Page, then recursively does the same for each child
        // control, which does the same for each of its child controls until the page and all controls are loaded.

        // Use the OnLoad event method to set properties in controls and establish database connections.

}

 

(6)Control (PostBack) event(s)

 

ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown’s selectedindexchange event, for example.

 

These are the events, the code for which is written in your code-behind class(.cs file).

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

 

protected void Button1_Click(object sender, EventArgs e)

{

   // This is just an example of control event.. Here it is button click event that caused the postback

}

 

(7)LoadComplete

 

This event signals the end of Load.

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

 

protected void Page_LoadComplete(object sender, EventArgs e)

{

        // Use this event for tasks that require that all other controls on the page be loaded.

}

 

(8)PreRender

 

Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.

 

For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called.

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

 

protected override void OnPreRender(EventArgs e)

{

        // Each data bound control whose DataSourceID property is set calls its DataBind method.

        // The PreRender event occurs for each control on the page. Use the event to make final
        // changes to the contents of the page or its controls.

}

 

(9)SaveStateComplete

 

Prior to this event the view state for the page and its controls is set.  Any changes to the page’s controls at this point or beyond are ignored.

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

 

protected override void OnSaveStateComplete(EventArgs e)

{

        // Before this event occurs,  ViewState has been saved for the page and for all controls. 
        // Any changes to the page or controls at this point will be ignored.

        // Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

}

 

(10)Render

 

This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

 

Note: Right click on the web page displayed at client’s browser and view the Page’s Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts.

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

// Render stage goes here. This is not an event

 

(11)UnLoad

 

This event is used for cleanup code. After the page’s HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object.

 

Cleanup can be performed on-

 

(a)Instances of classes i.e. objects

(b)Closing opened files

(c)Closing database connections.

 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

 

protected void Page_UnLoad(object sender, EventArgs e)

{

 // This event occurs for each control and then for the page. In controls, use this event to do final cleanup
        // for specific controls, such as closing control-specific database connections.

        // During the unload stage, the page and its controls have been rendered, so you cannot make further 
        // changes to the response stream.

               //If you attempt to call a method such as the Response.Write method, the page will throw an exception.

}

}

 

 
1 Comment

Posted by on September 22, 2013 in ASP Dot Net C#

 

Watermark on TextBox using JavaScript


Some time you need  watermark effect on Asp.net Text Box . then you use this code

JavaScript Code:

 

<script type = “text/javascript”>

    var defaultText = “Enter text here”;

    function WaterMarks(txt, evt)

    {

        if(txt.value.length == 0 && evt.type == “blur”)

        {

            txt.style.color = “gray”;

            txt.value = defaultText;

        }

        if(txt.value == defaultText && evt.type == “focus”)

        {

            txt.style.color = “black”;

            txt.value=””;

        }

    }

</script>

 

Above script will be called on onblur and onfocus events of the  Text Box.

The script does the following two checks

1. If the Text Box is empty and the event type is blur event it sets the watermark and changes the font color as Gray.

2. If the Text Box  matches default text and the event type is the focus it clears the Text Box and sets the font color as Black.

 

<asp:TextBox ID=”txtName” runat=”server” Text = “Enter text here”

    ForeColor = “Gray” onblur = “WaterMarks(this, event);”

    onfocus = “WaterMarks(this, event);”>

</asp:TextBox>

 

if Visual Studio will throw warning when you call client side event in the above way.so you need to call from code behind

txtName.Attributes.Add(“onblur”, “WaterMark(this, event);”);

txtName.Attributes.Add(“onfocus”, “WaterMark(this, event);”);  

 

 
Leave a comment

Posted by on August 29, 2013 in ASP Dot Net C#, Java Script

 

Tags: , ,

Alternating row color on repeater control


<style type=”text/css”>
.normalRow
{
background-color: #FCFCFC;
}
.alternateRow
{
background-color: #ECECEC;
}

</style>

<ul>

<asp:Repeater ID=”rpsize” runat=”server”  >
<ItemTemplate>
<li class='<%# Container.ItemIndex % 2 == 0 ? “normalRow” : “alternateRow” %>’ >

<span><%# Eval(“vchSizeName”) %></span>
</li>
</ItemTemplate>
</asp:Repeater>

</ul>

rowcolor

 
1 Comment

Posted by on August 29, 2013 in ASP Dot Net C#

 

Tags: , ,

How can I make URLs automatically hyperlinked on a web Google Doc


// if you want to open document with google doc viewer thien this article very helpfull for you.

//Header Section

<script>

$(document).ready(function () {
$(‘#document-slider-item’).click(
function (event) {

event.preventDefault();
var url = ‘http://docs.google.com/viewer?url=&#8217;;

url += $(this).attr(‘href’);
url += ‘&amp;embedded=true’;

var iframe = ”;

$(‘#document-viewer’).html(iframe);
});
});
</script>

 

//Body section

 

<body>
<form id=”form1″ runat=”server”>

<a id=”document-slider-item” href=”http://www.irs.gov/pub/irs-pdf/fw4.pdf&#8221; target=”_blank” style=”color:Red;font-weight:bold; font-size:larger;” >Click me</a>
<div style=”float:left” id=”document-viewer”>

</div>
</form>
</body>

 

 

 
Leave a comment

Posted by on August 26, 2013 in ASP Dot Net C#

 

Tags: , ,

Generate thumbnails from images in Asp.net


Hi,

This article very helpful for you to generate Thumbnails and also save in Directory path both Actual & thumb image.

 

Client Side:

 

 

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head id=”Head1″ runat=”server”>

<title>Generate a Thumbnails from Uploaded Image</title>

</head>

<body>

<form id=”form1″ runat=”server”>

<div>

<asp:FileUpload ID=”fileupload1″ runat=”server” />

<asp:Button ID=”btnsave” runat=”server” Text=”Upload” onclick=”btnsave_Click” />

</div>

<div>

<h1>Actual Images</h1>

<asp:DataList ID=”DataList1″ runat=”server” RepeatColumns=”3″ CellPadding=”5″>

<ItemTemplate>

<asp:Image ID=”Image1″ ImageUrl='<%# Bind(“Name”, “~/Images/{0}”) %>’ runat=”server” Height=”200px” Width=”200px” />

<br />

<asp:HyperLink ID=”HyperLink1″ Text='<%# Bind(“Name”) %>’ NavigateUrl='<%# Bind(“Name”, “~/Images/{0}”) %>’ runat=”server”/>

</ItemTemplate>

<ItemStyle BorderColor=”Brown” BorderStyle=”dotted” BorderWidth=”3px” HorizontalAlign=”Center”

VerticalAlign=”Bottom” />

</asp:DataList>

<h1>Thumbnail Images</h1>

<asp:DataList ID=”dtlist” runat=”server” RepeatColumns=”3″ CellPadding=”5″>

<ItemTemplate>

<asp:Image ID=”Image1″ ImageUrl='<%# Bind(“Name”, “~/Images/Thumbs/{0}”) %>’ runat=”server” />

<br />

<asp:HyperLink ID=”HyperLink1″ Text='<%# Bind(“Name”) %>’ NavigateUrl='<%# Bind(“Name”, “~/Images/Thumbs/{0}”) %>’ runat=”server”/>

</ItemTemplate>

<ItemStyle BorderColor=”Brown” BorderStyle=”dotted” BorderWidth=”3px” HorizontalAlign=”Center”

VerticalAlign=”Bottom” />

</asp:DataList>

</div>

</form>

</body>

</html>

 

Code Behind:

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

BindDataListThumbs();

BindDataList();

}

}

 

protected void BindDataListThumbs()

{

DirectoryInfo dir = new DirectoryInfo(MapPath(“Images/Thumbs”));

FileInfo[] files = dir.GetFiles();

ArrayList listItems = new ArrayList();

foreach (FileInfo info in files)

{

listItems.Add(info);

}

dtlist.DataSource = listItems;

dtlist.DataBind();

 

}

 

protected void BindDataList()

{

DirectoryInfo dir = new DirectoryInfo(MapPath(“Images”));

FileInfo[] files = dir.GetFiles();

ArrayList listItems = new ArrayList();

foreach (FileInfo info in files)

{

listItems.Add(info);

}

DataList1.DataSource = listItems;

DataList1.DataBind();

 

}

 

protected void btnsave_Click(object sender, EventArgs e)

{

 

 

string filename = Path.GetFileName(fileupload1.PostedFile.FileName);

// Save Narmal Image

fileupload1.SaveAs(Server.MapPath(“Images/” + filename));

 

string targetPath = Server.MapPath(“Images/Thumbs/” + filename);

Stream strm = fileupload1.PostedFile.InputStream;

var targetFile = targetPath;

//Based on scalefactor image size will vary

GenerateThumbnails(0.07, strm, targetFile);

BindDataListThumbs();

BindDataList();

}

private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)

{

using (var image = Image.FromStream(sourcePath))

{

var newWidth = 100; //(int)(image.Width * scaleFactor);

var newHeight = 75;// (int)(image.Height * scaleFactor);

var thumbnailImg = new Bitmap(newWidth, newHeight);

var thumbGraph = Graphics.FromImage(thumbnailImg);

thumbGraph.CompositingQuality = CompositingQuality.HighQuality;

thumbGraph.SmoothingMode = SmoothingMode.HighQuality;

thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);

thumbGraph.DrawImage(image, imageRectangle);

thumbnailImg.Save(targetPath, image.RawFormat);

}

}

 

 

Download sample code attached

https://skydrive.live.com/?cid=FCCA6A631A7CE903&id=FCCA6A631A7CE903%21886

 

 

 

thumbnails

 
Leave a comment

Posted by on August 6, 2013 in ASP Dot Net C#

 

Tags: , , , , ,

Image Zoom or enlarge using ASP.Net GridView control


In this Article you see  Image enlarge or zooming to an click on  Image  column on ASP.Net GridView control.

if you want to see small size image  of Gridview Row to see enlarge then this article very helpfull for you.if this helpful then kindly comment about that.

9e45058b

Concept of Idea

Here I’ll be adding Zoom functionality to all the images in the GridView so that user can click on that and view the enlarged image in a modal div .

 

Add DIV

First you need to add the two DIV on Asp.net page where you place gridview.

 

<div id=”divBackground”>

</div>

<div id=”divImage”>

    <table style=”height: 100%; width: 100%”>

        <tr>

            <td valign=”middle” align=”center”>

                <img id=”imgLoader” alt=””

                 src=”images/loader.gif” />

                <img id=”imgFull” alt=”” src=””

                 style=”display: none;

                height: 500px;width: 590px” />

            </td>

        </tr>

        <tr>

            <td align=”center” valign=”bottom”>

                <input id=”btnClose” type=”button” value=”close”

                 onclick=”HideDiv()”/>

            </td>

        </tr>

    </table>

</div>

 

 

The First DIV divBackground will act as a modal DIV and will freeze the screen. The second DIV divImage will be used to display the enlarged image. You will notice the image which I have added to provide a loading in progress until the image is completely loaded. The below image displays the loading of an image.

 

when you Click to enlarge image

a156c83d-40a1-41fb-bca1-c84a049b10ff

Adding the CSS

You will need to add the following CSS in the head section of the page or in the CSS file

 

<style type=”text/css”>

     body

     {

        margin:0;

        padding:0;

        height:100%;

     }

     .modal

     {

        display: none;

        position: absolute;

        top: 0px;

        left: 0px;

        background-color:black;

        z-index:100;

        opacity: 0.8;

        filter: alpha(opacity=60);

        -moz-opacity:0.8;

        min-height: 100%;

     }

     #divImage

     {

        display: none;

        z-index: 1000;

        position: fixed;

        top: 0;

        left: 0;

        background-color:White;

        height: 550px;

        width: 600px;

        padding: 3px;

        border: solid 1px black;

     }

   </style>

 

Adding the JavaScript on Same Page

JavaScript function that will display the modal DIV when the Image in the ASP.Net GridView Control is clicked.

<script type=”text/javascript”>

 function LoadDiv(url)

 {

    var img = new Image();

    var bcgDiv = document.getElementById(“divBackground”);

    var imgDiv = document.getElementById(“divImage”);

    var imgFull = document.getElementById(“imgFull”);

    var imgLoader= document.getElementById(“imgLoader”);

 

    imgLoader.style.display = “block”;

    img.onload = function() {

        imgFull.src = img.src;

        imgFull.style.display = “block”;

        imgLoader.style.display = “none”;

    };

    img.src= url;

    var width = document.body.clientWidth;

    if (document.body.clientHeight > document.body.scrollHeight)

    {

        bcgDiv.style.height = document.body.clientHeight + “px”;

    }

    else

    {

        bcgDiv.style.height = document.body.scrollHeight + “px” ;

    }

 

    imgDiv.style.left = (width-650)/2 + “px”;

    imgDiv.style.top =  “20px”;

    bcgDiv.style.width=”100%”;

   

    bcgDiv.style.display=”block”;

    imgDiv.style.display=”block”;

    return false;

 }

 function HideDiv()

 {

    var bcgDiv = document.getElementById(“divBackground”);

   var imgDiv = document.getElementById(“divImage”);

    var imgFull = document.getElementById(“imgFull”);

    if (bcgDiv != null)

    {

        bcgDiv.style.display=”none”;

        imgDiv.style.display=”none”;

        imgFull.style.display = “none”;

    }

 }

</script>

Above are the two functions that will take care of all the functions needed. The LoadDiv function as the name that loads the modal background DIV and the Image DIV with the enlarged image. This function gets called when the Image in the GridView is clicked.

An important line I need to point out is this

imgDiv.style.left = (width-650)/2 + “px”;

 

As you will notice I have used a number 650 here. 650 is the width of the Image DIV in order to align it at the center of the screen I am subtracting it from the browser Viewport width and then taking the average.

The HideDiv function simply gets called when the Close Button is clicked on the Image DIV. It simply hides the DIV and unfreezes the screen.

 

Calling JavaScript from ASP.Net GridView Control

The only difference from my previous article is that I have used Image Control in Template Field instead of ImageField. Refer the GridView below

 

 

 

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”false”

  Font-Names=”Arial”>

<Columns>

    <asp:BoundField DataField=”ID” HeaderText=”ID” />

    <asp:BoundField DataField=”FileName” HeaderText=”Image Name” />

    <asp:TemplateField HeaderText=”Preview Image”>

        <ItemTemplate>

            <asp:ImageButton ID=”ImageButton1″ runat=”server”

            ImageUrl='<%# Eval(“FilePath”)%>’ Width=”100px”

            Height=”100px” Style=”cursor: pointer”

            OnClientClick = “return LoadDiv(this.src);”

            />

        </ItemTemplate>

    </asp:TemplateField>

</Columns>

</asp:GridView>

 

 

 

when you  calling the LoadDiv function in the OnClientClick event of ASP.Net ImageButton. It is important to return false from the JavaScript function to avoid postbacks. In the figure below you can view the enlarged image being displayed

 

Click to enlarge image

 

 

 

Zoom

 

That’s it we come to an end. Hope you liked it. Download the related source code using the link below.

https://skydrive.live.com/?cid=fcca6a631a7ce903#cid=FCCA6A631A7CE903&id=FCCA6A631A7CE903!883

 

 
Leave a comment

Posted by on July 30, 2013 in ASP Dot Net C#

 

Tags: , , , , , ,

How to display the questions with their answers


Hello ,

if you want to develop application like MCQ or Survey Conduct  Web Application Project then use below mention code and also i add complete project code . i search on that lot of time to how to implement & validation . i think this Article very helpful for you.

surveyimgClient Side:

.css

 

<style type=”text/css”>
.questiontext {
background-color: #EEF6FF;
font-family: verdana;
font-size: 12px;
font-weight: bold;
padding: 0.5em 1em;
text-align: left;
}
.radioButtonList{ list-style-type: none;
margin: 0 0 0.5em 0.5em;
text-align: left;
}

.coa-button {
background-color: #9AC51D;
background-image: -moz-linear-gradient(center top , #9AC51D, #7C9F17);
border: 1px solid #759716;
border-radius: 3px 3px 3px 3px;
color: #FFFFFF;
display: block;
padding: 7px 0;
text-align: center;
text-decoration: none !important;
width: 189px;
}
</style>

 

:: Following  below  repeater code to show all Surveys

 

<asp:Repeater id=”Repeaterforselect” runat=”server”
onitemcommand=”Repeaterforselect_ItemCommand” >

<ItemTemplate>

<li>

<i><%#(((RepeaterItem)Container).ItemIndex+1).ToString()%></i>
<asp:LinkButton ID=”LinkButton1″ runat=”server” Text='<%#Eval(“title”)%>’ CommandName=”Click”

CommandArgument='<%# Eval(“id”)%>’ >

</asp:LinkButton>

</li>

</ItemTemplate>

</asp:Repeater>

 

:: Following  below  DataList  code to show selected  Survey Question & option answer

<asp:DataList ID=”dtlQuestions” runat=”server” RepeatDirection=”Vertical” DataKeyField=”ID” OnItemDataBound=”dtlQuestions_ItemDataBound” Width=”630px”>
<ItemTemplate>
<div >
<asp:Label ID=”Label2″ Text='<%#(((DataListItem)Container).ItemIndex+1).ToString()%>’ Runat=”server”/>
<asp:Label ID=”q” runat=”server” Text='<%# Eval(“questions”) %>’ CssClass=”questiontext”></asp:Label> <asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server”
ErrorMessage=”Required” ForeColor=”Red” ControlToValidate=”dtlAnswers” ValidationGroup=”Bla”></asp:RequiredFieldValidator>
<asp:HiddenField ID=”hnQuestionsid” runat=”server” Value='<%# DataBinder.Eval(Container.DataItem, “Questionsid”)%>’ />
</div>
<br />
<asp:RadioButtonList ID=”dtlAnswers” runat=”server” ValidationGroup=”Bla” RepeatDirection=”Vertical” RepeatColumns=”1″ CssClass=”radioButtonList”>

</asp:RadioButtonList>
</ItemTemplate>
</asp:DataList>

 

:: Submit Button Handle with validation, without selection any question data not insert into database.

 

<asp:Button ID=”btnSubmit” runat=”server” onclick=”btnSubmit_Click”

ValidationGroup=”Bla” CssClass=”coa-button” Width=”100px” style=”float:right;margin-right:150px;” Visible=false
Text=”Submit”  />

 

Server Side:

 

string connectionString = ConfigurationManager.ConnectionStrings[“ApplicationServices”].ToString();
SqlConnection conn;
SqlCommand cmd = new SqlCommand();

////Load All Survey on Page Load

protected void Page_Load(object sender, EventArgs e)
{

conn = new SqlConnection(connectionString);

if (!Page.IsPostBack)
{

hdnsurveyformswomp.Value = “0”;

loadSurvey();

}
}

// Fill Repeater Control to All Survey

public void loadSurvey()
{

string connectionString = ConfigurationManager.ConnectionStrings[“ApplicationServices”].ToString();

DataSet ds = new DataSet();

ds = SqlHelper.ExecuteDataset(connectionString, System.Data.CommandType.StoredProcedure, “surveysselect”);
if (ds.Tables[0].Rows.Count > 0 && ds != null)
{
Repeaterforselect.DataSource = ds;
Repeaterforselect.DataBind();
}

}

// At this Event we Load Question & option answer on Each Survey Click to fill datalist
protected void Repeaterforselect_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case “Click”:
//get command argument here
string id = e.CommandArgument.ToString();
loadQuestion(id);

break;
}

}

// Load Question against Survey

public void   loadQuestion(string id)
{

string connectionString = ConfigurationManager.ConnectionStrings[“ApplicationServices”].ToString();

DataSet ds = new DataSet();

SqlParameter[] paramArray = new SqlParameter[] {
new SqlParameter(“@id”,Convert.ToInt32(id)),

};

ds = SqlHelper.ExecuteDataset(connectionString, System.Data.CommandType.StoredProcedure, “SurveyFormsWOMPretrive”, paramArray);
if (ds.Tables[0].Rows.Count > 0)
{

Label1.Text = ds.Tables[0].Rows[0][“title”].ToString();
hnSurveyid.Value = ds.Tables[0].Rows[0][“surveysid”].ToString();
dtlQuestions.DataSource = ds;
dtlQuestions.DataBind();
btnSubmit.Visible = true;
}

else
{
Label1.Text = “No Record Found”;
dtlQuestions.DataSource = null;
dtlQuestions.DataBind();
btnSubmit.Visible = false;
}

}

 

// Fill DataList RaiobuttonDropdownList against each Question

protected void dtlQuestions_ItemDataBound(object sender, DataListItemEventArgs e)
{

DataListItem drv = e.Item.DataItem as DataListItem;
RadioButtonList RadioButtonList1 = (RadioButtonList)e.Item.FindControl(“dtlAnswers”);
HiddenField hnQuestionsid = (HiddenField)e.Item.FindControl(“hnQuestionsid”);
DataSet ds = loadQuestionOptionbyqid(hnQuestionsid.Value);
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
RadioButtonList1.DataSource = ds;
RadioButtonList1.DataTextField = “question_option”;
RadioButtonList1.DataValueField = “question_id”;
RadioButtonList1.DataBind();
}

}

// Load Question Option in Radiobuttonlist

 
public DataSet loadQuestionOptionbyqid(string id)
{

string connectionString = ConfigurationManager.ConnectionStrings[“ApplicationServices”].ToString();

DataSet ds = new DataSet();

SqlParameter[] paramArray = new SqlParameter[] {
new SqlParameter(“@id”,Convert.ToInt32(id)),

};

return SqlHelper.ExecuteDataset(connectionString, System.Data.CommandType.StoredProcedure, “Surveyquestionchoisebyqstid”, paramArray);

}
/// Submit Selected Question to db

 
protected void btnSubmit_Click(object sender, EventArgs e)
{

//Data save
//  count = 0;
if (dtlQuestions.Items.Count > 0)
{
foreach (DataListItem li in dtlQuestions.Items)
{
RadioButtonList rdList = li.FindControl(“dtlAnswers”) as RadioButtonList;
HiddenField hnQuestionsid = (HiddenField)li.FindControl(“hnQuestionsid”);
foreach (ListItem answer in rdList.Items)
{
bool isSelected = answer.Selected; if (isSelected) { int slval = Convert.ToInt32(answer.Value); InsertSurveyData(Convert.ToInt32(hnSurveyid.Value), Convert.ToInt32(hnQuestionsid.Value), Convert.ToInt32(slval)); }
}
}
}

Response.Redirect(“thanksyou.aspx”);

}

/// Insert Function

 

private void InsertSurveyData(int sid, int qid, int qoptid)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = “SubmitSurveyForminsert”;
//simple hiden field no repeater
cmd.Parameters.Add(“@Surveyid”, SqlDbType.Int).Value = sid;
cmd.Parameters.Add(“@Questionid”, SqlDbType.Int).Value = qid;
cmd.Parameters.Add(“@surveyQuestionOptionid”, SqlDbType.Int).Value = qoptid;

cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();

conn.Close();

}

 

 

// Complete Application Code With database Script

 

https://skydrive.live.com/?cid=FCCA6A631A7CE903&id=FCCA6A631A7CE903%21880

 

 
2 Comments

Posted by on July 24, 2013 in ASP Dot Net C#

 

Tags: , , ,