ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: How to Increase The Overall Performance of ASP.NET 4.5.1 in your App

clock October 1, 2014 07:23 by author Ben

ASP.NET is really a framework for creating net applications created by Microsoft. Initially the technologies. NET is the successor of ASP which is also a computer software product from Microsoft. With .NET ASP gives a platform for developers to design and create dynamic websites and net portals.



You will find certain items that ought to be regarded as when improving the performance from the application in developing a net application. Here are a few of the tips to improve the performance of ASP.NET 4.5.1:

Turn off Session State
Disable session state if you do not need, as this can improve the all round efficiency. By default the session state is always active. However, you'll be able to disable session state for any specific pages.

Turn off Tracing
If tracing is enabled, tracing will add a whole lot of overhead in producing applications. Though tracing is actually a useful function inside the development because it enables developers to track and trace application sequence, tracing may be turned off, unless you want to monitor the trace logging.

Avoid Page Validation Server (Steer clear of Server-side Validation)
Within this case, must be attempted use of client-side validation, not the server side. Server-side validation will consume a lot of sources around the server which can have an effect on application efficiency.

Stay away from Exceptions (Avoid Exceptions)
Exceptions may be 1 of the biggest resource eater which resulted within the lower of web applications and windows applications. Therefore, it is much better to prevent the use and handling of exceptions which can be not beneficial.

Avoid frequent connections for the database (Steer clear of Frequent Calls to Database)
Connections are frequently made for the database can devote time response and resources (resources). This can be avoided by utilizing batch processing. Producing the minimum database connection as a connection is opened and not closed, may cause efficiency slowdown.

Stay away from utilizing Recursive Functions and Nested Loops
To improve application performance, attempt to always steer clear of utilizing nested loops and recursive functions simply because these functions consume a whole lot of memory.

Turn off the View State

In ASP.NET, the default view state will probably be active and will slow down the website. So if you don't use a kind postback, it's much better to disable view state.

Use Caching
Web page caching could be employed to get a particular period of time and towards the required duration will not visit the server and are served from the cache. In the case of static internet pages and dynamic, Partial Caching [Fragment Caching] may be utilized to break into a couple of pages a user control.



ASP.NET 4.5.1 Windows Cloud Hosting - With ASPHostPortal.com :: How to Transferring User Accounts from ASP.NET to MojoPortal

clock April 10, 2014 08:24 by author Kenny

MojoPortal is a free and open source content management system that allows you to maintain your Web site with no HTML coding knowledge. When you need to build a web application you usually have some business functionality in mind but there is always a certain amount of web plumbing that needs to be implemented for things like navigation, authentication of users, security and roles and other things that are needed to support most kinds of business application logic. Sometimes we need to transfer user accounts from existing ASP.NET membership based sites into MojoPortal. So, in this article i will explain about how to transferring user accounts from ASP.NET to MojoPortal.

For the first step, you must set MojoPortal to use plain text passwords.
And then, create a folder on your PC to contain the scripts > in this folder create the following .bat files:

CreateMojoUserTablesXMLFormats.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set database=[Databasename].[Schema].
set switches= -c -x
set formatDir=[Full path to formats directory with trailing slash]
bcp %database%mp_Users format nul %login% %switches% -f
%formatDir%mojoUsers.xml
bcp %database%mp_UserProperties format nul %login% %switches% -f
%formatDir%mojoUserProperties.xml
bcp %database%mp_userRoles format nul %login% %switches% -f
%formatDir%mp_userRoles.xml


ExportASPNETUserData.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set dataDir=[Full path to data directory with trailing slash]
set database=[Databasename].[Schema].
set switches= -k –c
bcp "SELECT 0 AS UserID, 1 AS SiteID, aspnet_Users.Username AS Name,
aspnet_Users.UserName AS LoginName, COALESCE
(aspnet_Membership.Email,aspnet_Users.UserName + [email protected]' ) AS
Email, aspnet_Membership.LoweredEmail AS LoweredEmail, NULL AS
PasswordQuestion, NULL AS PasswordAnswer, NULL AS Gender,
aspnet_Membership.IsApproved AS ProfileApproved, NULL AS RegisterConfirmGUID,
aspnet_Membership.IsApproved AS ApprovedForForums, 0 AS Trusted, CASE
aspnet_Roles.RoleName WHEN 'xg' THEN 0 ELSE 1 END AS DisplayInMemberList, NULL
AS WebsiteURL, NULL AS Country, NULL AS [State], NULL AS Occupation, NULL AS
Interests, NULL AS MSN, NULL AS Yahoo, NULL AS AIM, NULL AS ICQ, 0 AS
TotalPosts, NULL AS AvatarURL, 0 AS TimeOffsetHours, NULL AS [Signature],
aspnet_Membership.CreateDate AS DateCreated, aspnet_Membership.UserId AS
userGUID, NULL AS Skin, 0 AS IsDeleted, aspnet_Users.LastActivityDate AS
LastActivityDate, aspnet_Membership.LastLoginDate AS LastLoginDate, NULL AS
LastPasswordChangedDate, NULL AS LastLockoutDate, 0 AS
FailedPasswordAttemptCount, NULL AS FailedPwdAttemptWindowStart, 0 AS
FailedPwdAttemptCount, NULL AS FailedPwdAnswerWindowStart,
aspnet_Membership.IsLockedOut AS IsLockedOut, NULL AS MobilePin, NULL AS
PasswordSalt, NULL AS Comment, NULL AS OpenIDURI, NULL AS WindowsLiveID,
'77C33D82-D6F0-49ED-95A7-84C11919AD94' AS SiteGUID, NULL AS TotalRevenue,
userInfo.ForeName AS FirstName, userInfo.Surname AS LastName,
aspnet_Users.Username as Pwd, 1 AS MustChangePassword, NULL AS NewEmail, NULL
AS EditorPreference, '00000000-0000-0000-0000-000000000000' AS EmailChangeGuid,
NULL AS TimeZoneID, '00000000-0000-0000-0000-000000000000' AS PasswordResetGuid
FROM %database%aspnet_Membership INNER JOIN %database %aspnet_Users ON
aspnet_Membership.UserId=aspnet_Users.UserId INNER JOIN %database%userInfo on
aspnet_Membership.UserId=userInfo.userId INNER JOIN
%database%aspnet_UsersInRoles ON
aspnet_Membership.UserId=aspnet_UsersInRoles.UserId INNER JOIN
%database%aspnet_Roles ON aspnet_UsersInRoles.RoleId =
aspnet_Roles.RoleId" queryout %dataDir%lharUsers.txt %switches% %login% -o
output/usersOutput.txt
bcp "select RoleName,UserId from %database%aspnet_Roles INNER JOIN
%database%aspnet_UsersInRoles on
aspnet_Roles.RoleId=aspnet_UsersInRoles.RoleId" queryout
%dataDir%lharUsersRoles.txt %switches% %login% -o output/userRolesOutput.txt
bcp "SELECT newid() AS PropertyID, UserId AS userGUID, [String to use
as MojoPortal PropertyName] AS PropertyName, Title AS PropertyValueString,
NULL AS PropertyValueBinary, GETDATE() AS LastUpdatedDate, 0 AS IsLazyLoaded
FROM %database%UserInfo
UNION ALL
SELECT newid() AS PropertyID, UserId AS userGUID, [String to use as
MojoPortal PropertyName] AS PropertyName, Title AS PropertyValueString,
NULL AS PropertyValueBinary, GETDATE() AS LastUpdatedDate, 0 AS IsLazyLoaded
FROM %database%UserInfo" queryout %dataDir%lharUserProfiles.txt %switches%
%login% -o output/userPropertiesOutput.txt


ImportMojoPortalUserData.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set database=[Databasename].[Schema].
set dataDir=[Full path to data directory with trailing slash]

set switches= -k -R

set formatDir=[Full path to outputs directory with trailing slash]

bcp %database%mp_users IN %dataDir%lharUsers.txt %login% %switches% -f %formatDir%mojoUsers.xml -o output/importUsers.txt

bcp %database%mp_userProperties IN %dataDir%lharUserProfiles.txt %login% %switches% -f %formatDir%mojoUserProperties.xml -o output/importUserProperties.txt

bcp %database%mp_userRoles IN %dataDir%lharUsersRoles.txt %login% %switches% -f %formatDir%mp_userRoles.xml -o output/importUserRoles.txt


Next step is, create the following subdirectories in this folder: data, formats, output.
After create the CreateMojoUserTablesXMLFormats.bat file and the ExportASPNETUserData.bat file, run these program.
Don’t forget to check the output directory for any errors and check the data files have been created and contain the data you expect.
After that, run the ImportMojoPortalUserData.bat. Check the output directory for any errors and check the database tables have the data.
Switch MojoPortal back to using encrypted passwords and the last test a few logins.



Free Trial ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: How to Send Bulk Email Using ASP.Net 4.5

clock April 3, 2014 12:14 by author Kenny

In this article I’m going to explain about how to send bulk email using ASP.Net 4.5. Bulk email software is software that is used to send email in large quantities. Bulk mail broadly refers to mail that is mailed and processed in bulk at reduced rates. The term does not denote any particular purpose for the mail; but in general usage is synonymous with "junk mail". This tutorial we will use ASP.NET Web Page for provide the user interface for your Web applications, Grid View for enables you to select, sort, and edit values of a data source in a table where each column represents a field and each row represents a record, HTML Email Templates and Gmail SMTP Mail Server.

Let’s start to try this tutorial, for the first step you must create a new project.
Click "File" -> "New" -> choose "Project..." and then select web "ASP .Net Web Forms Application". Name it as "Bulk Email".
And now let’s see in the Design page “Default.aspx” design the web page as in the following screen:

This is code for Design Source (Default.aspx):
Default.aspx.cs

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="BulkEmail._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">              
                <h2>Send Bulk email using asp.net</h2>
            </hgroup>
            <p>To learn more about ASP.NET
            </p>
        </div>
    </section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
       <h3>We suggest the following:</h3>
    <asp:Panel ID="Panel1" runat="server" Width="100%" ScrollBars="Horizontal">
    <p>
       <asp:Button ID="btnBind" runat="server" Text="View" OnClick="btnBind_Click" /> <asp:Label
ID="Label1" runat="server" Font-Bold="true" ForeColor="Green" Text="Total
Customers:">   
</asp:Label><asp:Label ID="lbltotalcount" runat="server" ForeColor="Red" Font
Size="Larger"></asp:Label> </p>
        <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
        <asp:GridView ID="grvCustomers" runat="server"></asp:GridView>
    </asp:Panel>
</asp:Content>

In the Web.config file create the connection string as:
Web.config

<connectionStrings>   
<add name="ConnectionString"connectionString="Server=localhost;userid=root;password=;Database=
orthwind"providerName="MySql.Data.MySqlClient"/>      
</connectionStrings>


In the code behind file (Default.aspx.cs) write the code as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//Using namespaces 
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Data;

namespace BulkEmail
{
    public partial class _Default : Page
    {
        #region MySqlConnection Connection
        MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            Try
            {
                if (!Page.IsPostBack)
                {

                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
        #endregion
        #region show message
        /// <summary>
        /// This function is used for show message.
        /// </summary>
        /// <param name="msg"></param>
        void ShowMessage(string msg)
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
language='javascript'>alert('" + msg + "');</script>");
        }       
        #endregion
        #region Bind Data
        /// <summary>
        /// This display the data fetched from the table using MySQLCommand,DataSet and
MySqlDataAdapter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBind_Click(object sender, EventArgs e)
        {
            Try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("Select
CustomerID,ContactName,Address,Phone,Email from customers", conn);
                MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                grvCustomers.DataSource = ds;
                grvCustomers.DataBind();
                lbltotalcount.Text = grvCustomers.Rows.Count.ToString();
            }
            catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
            Finally
            {
                conn.Close();

            }
            btnBind.Visible = false;
        }
        #endregion
        #region Bulk email,GridView,gmail
        /// <summary>
        /// this code used to Send Bulk email 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSend_Click(object sender, EventArgs e)
        {
            Try
            {
                lbltotalcount.Text = string.Empty;
                foreach (GridViewRow grow in grvCustomers.Rows)
               {
                    string strCustomerID = grow.Cells[0].Text.Trim();
                    string strContactName = grow.Cells[1].Text.Trim();
                    string strAddress = grow.Cells[2].Text.Trim();
                    string strPhone = grow.Cells[3].Text.Trim();
                    string strEmail = grow.Cells[4].Text.Trim();               

                    string filename = Server.MapPath("~/Event.html");
                    string mailbody = System.IO.File.ReadAllText(filename);
                    mailbody = mailbody.Replace("##NAME##", strContactName);
                    string to = strEmail;
                    string from = "[email protected]";
                    MailMessage message = new MailMessage(from, to);
                    message.Subject = "Auto Response Email";
                    message.Body = mailbody;
                    message.BodyEncoding = Encoding.UTF8;
                    message.IsBodyHtml = true;
                    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                    System.Net.NetworkCredential basicCredential = newSystem.Net.NetworkCredential("[email protected]", "Password");
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = true;
                    client.Credentials = basicCredential;
                    try
                    {
                        client.Send(message);
                        ShowMessage("Email Sending successfully...!" + strContactName + " &nbsp;");                                           
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                    }
                } 
            }
            catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
            Finally
            {
                conn.Close();
            }
        }
        #endregion
    }
}


Finally, Bulk Sending an E-Mail Using ASP.NET 4.5 with HTML Email Templates and Gmail SMTP Mail Server.



ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: Capture images using web camera in ASP.NET 4.5.1

clock March 25, 2014 09:11 by author Kenny

In this article, i'm going to explain about how to integrate a webcam into your web application using ASP.NET 4.5.1. A web camera can capture images at the server end and a web page can display them. It’s very simple for integrate a webcam and capture images in your website that using ASP.NET 4.5.1.

Before it, make sure that your device has Latest Flash player and Web camera.
Let's following these steps:

First, copy the “WebcamResources” into your new application.
After that, add the following code in to your Default.aspx page:
<object width="450" height="200"param name="movie1" value="WebcamResources/save_picture.swf"

embed src="WebcamResources/save_picture.swf" width="45
0"
height="200" >
</object>

This code will place your Flash object into your web page, used to capture the images from the web cam.
Add one more page there with the name ImageConversions.aspx.
Add the following code into ImageConversion.aspx at the page load event:
string str_Photo = Request.Form["image_Data"]; //Get the image from flash file
byte[] photo = Convert.FromBase64String(str_Photo);
FileStream f_s = new FileStream("C:\\capture.jpg", FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter b_r = new BinaryWriter(f_s);
b_r.Write(photo);
b_r.Flush();
b_r.Close();
f_s.Close();


The above code will convert the bytes to an image and will save the image in the c drive.



FreeTrial ASP.NET 4.5.1 Hosting :: How to Make Web Chat Box Using ASP.NET

clock March 19, 2014 07:19 by author Kenny

You can get your chat box on your website using ASP.NET. The advantage of chat box is make websites and web applications more user interactive and provide a dynamic look too. The functionality of chat box in a website is increasing day by day, because it provides some extra functionalities and looks.

Now, we will explain about how to make Chat Box using ASP.NET.
For the first, Open Visual Studio>Create a new page (class file)
And then, Design your chat box (through HTML and CSS).

Coding (as shown below):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Window1.Visible = true;
    }
 
    private string Chat
    {
        get
        {
            if (Application["a"] == null)
                Application["a"] = "";
            return Application["a"].ToString();
        }
        set
        {
           Application["a"] = value;
        }
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        Label1.Text = Chat;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Chat = TextBox1.Text +"<br/>"+ Chat;
    }
}


The chat box code that we explain here is a combination of GAIA Toolkit and Coding. We are doing this coding in C#.

 



ASP.NET 4.5.1 - with ASPHostPortal.com :: How to Convert PDF to Excel in ASP.NET

clock March 6, 2014 11:45 by author Kenny

Well, i will explain the best way to convert PDF to Excel in .NET Framework.
When dealing with digital documents, you may notice that PDF data and Excel spreadsheets often go hand in hand. Although not as easily as we’d like. The PDF format is perfect format for preservation of your content layout - whether it be an invoice, a statement or a database. Thus, even though the format can display data perfectly, it can also make it difficult to reuse, edit or analyze in Microsoft Excel. Users have no choice but to turn to PDF converter solutions.

For developers, this presents a perfect opportunity: you can provide a solution within your own applications. In fact, one developer tool, PDF2Excel SDK, will allow you to integrate PDF to Excel conversion technology into your existing software applications and projects.

Developed by Investintech.com, PDF2Excel SDK contains everything a developer needs to leverage the same conversion algorithm behind their desktop PDF converter via DLL or COM API. This introduction guide to PDF2Excel SDK will give you a closer look at their PDF to Excel 2007 conversion technology.


Implementation Methods

For those who are programming with C#, use the following methods to convert PDF to Excel.

1. Using the Function Library

Prior to using the PDF-To-Excel function library, you must declare the functions in a class:

Note: if the full path is not specified, the location of the DLL file has to be defined within the system variable named PATH. Alternatively the file should be placed in the same location as the .exe file which is using it.

2. Using the COM Server

Prior to using the PDF-To-Excel COM Server, you must define a project reference to the PDF2ExcelCom 1.0 COM Component.
The .NET COM Interop layer generates a wrapper class you may call in your code.



ASP.NET 4.5.1 with ASPHostPortal.com :: Application Development A Perfect Web App Master

clock March 3, 2014 07:48 by author Kenny

ASP.NET is a development framework for building web pages and web sites with HTML, CSS, JavaScript and server scripting. ASP.NET helps bring out dynamism with web pages, all in a very short turn around time. This is why it is known to be a unique as well as a very popular framework, especially when web apps or websites are built. The reason why this framework was developed by Microsoft is because the market admires its innovative features. So, it has gained importance and is special as well. Consider it as a tool which can work wonders for developers as well as programmers, since it allows beautiful along with very dynamic websites to be born, using C# or VB as languages.

.net development services In the days gone by, web page contents weren’t spared of being static. With time it was understood that changes were important and have to be made for the websites to survive. New content had to be brought in. Moreover, there were manual modifications to be made to keep the site on the run as well as updated. This then brought about the awareness of having sites that would be auto updated as well as dynamic. Therefore, ASP by Microsoft was brought in, and hence the name ACTIVE SERVER PAGES came about. It thus helped in more ways than one, especially in meeting such needs.

Benefits

  1. You could own a small medium enterprise online or managing a huge business across many networks. There are many beneficial features which can help you to reach your goals.
  2. Irrespective of the size or volume, the language would work on every performance problem. It is developed in such a way that apps now can be worked on from any corner of the globe with utmost efficiency.
  3. Using this language, one doesn’t have to engage in long coding to make large apps. Most popular sites including ecommerce sites use it without any difficulty. This is because there is more power along with greater flexibility. In fact, the web pages can use the html code as well as source code for enhanced dynamism.
  4. In this day and age, using Asp.net for web apps is the sure shot way of making it big, say experts. The language is independent, with more than a quarter .net languages for users as well as developers to thrive on and to work with for their web apps.
  5. Infinite loops, memory leads or any activity deemed illegal would be instantly checked on. restarts happen on the spot, wherein all illegal activity along with its source would be tarnished.
  6. Before anything is sent to the main browser, the code would run on the esteemed server. This then ensures that there is constant monitoring of the pages, its main components as well as all the important applications in it.
  7. Cheap framework, and those looking for cost effective solutions would gain widely from it.


If you take a look online, you would find a large number of offshore companies across the world, willing and waiting to help your venture with all Asp.net needs. Most companies prefer their services outsourced, because of reliability as well as efficiency. Outsourced teams are available with plenty of expertise and experience to help with Asp.net application development and maintenance too.


The face of Asp.net app development is known to be an area which is fast emerging across the IT industry, say experts. Even the non IT companies look at it for safety and security in business across the online world. Verticals therefore are changing, and it is very rapid. Right from education to retail, manufacturing to finance, banking or investment, even online ecommerce sites too, everyone is using Asp.net.

Asp.net helps with continuity, smooth functioning and also gels well with a wide range of systems to meet every edge and demands of the business world these days. With super high web apps on the go, clients as well as customers alike are deriving immense satisfaction. Companies can now showcase their products and services like never before, there by bringing in more money.

 



ASP.NET 4.5.1 - with ASPHostPortal.com :: How to Create Dynamic DropDownLists in ASP.NET 4.5.1

clock February 26, 2014 06:23 by author Kenny

Now i will tell you how to create Dynamic DropDownLists in ASP.NET 4.5.1

Object:

1. Create dropdownlist dynamically with autopostback property true
2. Keep dropdownlist during postback
3. Maintain selected value during postback.
Here is the sample for this.

In aspx page:
<form
id="form1" runat="server">

    <div>

        <asp:Table ID="tbl" runat="server">

        </asp:Table>

        <asp:Button ID="btnSet" runat="server" Text="Button" onclick="btnSet_Click" /> </div>

    </form>

To Create Dynamic Dropdownlist:

protected
void Page_Load(object sender, EventArgs e)

{

    if (!Page.IsPostBack)

    {

    CreateDynamicTable();

    }

}

    private void CreateDynamicTable()

    {  

        // Fetch the number of Rows and Columns for the table

        // using the properties

        int tblRows = 3;

        int tblCols = 3;

        // Now iterate through the table and add your controls

        for (int i = 0; i < tblRows; i++)

        {

            TableRow tr = new TableRow();

            for (int j = 0; j < tblCols; j++)

            {

                TableCell tc = new TableCell();

                DropDownList ddl = new DropDownList();

                ddl.ID = "ddl-" + i.ToString() + "-" + j.ToString();

                for (int k = 0; k < 5; k++)

                {

                    ddl.Items.Add(new ListItem("item-"+k.ToString(),k.ToString())); 

                }

                ddl.AutoPostBack = true;

                ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);

                // Add the control to the TableCell

                tc.Controls.Add(ddl);

                // Add the TableCell to the TableRow

                tr.Cells.Add(tc);

            }

            // Add the TableRow to the Table

            tbl.Rows.Add(tr);

            tbl.EnableViewState = true;

            ViewState["tbl"] = true;

        }

    }

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)

    {

    // what you want to perform    

    }

To retrieve value on button click:

protected
void btnSet_Click(object sender, EventArgs e)

    {

        foreach (TableRow tr in tbl.Controls )

        {

            foreach (TableCell tc in tr.Controls)

            {

                if (tc.Controls[0] is DropDownList)

                {

                    Response.Write(((DropDownList)tc.Controls[0]).SelectedItem.Text+" ");        

                }

            }

            Response.Write("<br/>"); 

        }

    }
Right Now, No output because dynamic controls are lost in postback then what to do.

So we need to save dynamic controls value and generate dynamic controls again.we need to maintain viewstate.

protected
override object SaveViewState()

{

    object[] newViewState = new object[2];

    List<string> txtValues = new List<string>();

    foreach (TableRow row in tbl.Controls)

    {

        foreach (TableCell cell in row.Controls)

        {

            if (cell.Controls[0] is DropDownList)

            {

                txtValues.Add(((DropDownList)cell.Controls[0]).SelectedIndex.ToString());

            }

        }

    }

    newViewState[0] = txtValues.ToArray();

    newViewState[1] = base.SaveViewState();

    return newViewState;

}

protected override void LoadViewState(object savedState)

{

    //if we can identify the custom view state as defined in the override for SaveViewState

    if (savedState is object[] && ((object[])savedState).Length == 2 && ((object[])savedState)[0] is string[])

    {

        object[] newViewState = (object[])savedState;

        string[] txtValues = (string[])(newViewState[0]);

        if (txtValues.Length > 0)

        {

            //re-load tables

            CreateDynamicTable();

            int i = 0;

            foreach (TableRow row in tbl.Controls)

            {

                foreach (TableCell cell in row.Controls)

                {

                    if (cell.Controls[0] is DropDownList && i < txtValues.Length)

                    {

                        ((DropDownList)cell.Controls[0]).SelectedIndex = Convert.ToInt32(txtValues[i++]);

                    }

                }

            }

        }

        //load the ViewState normally

        base.LoadViewState(newViewState[1]);

    }

    else

    {

        base.LoadViewState(savedState);

    }

}



ASP.NET 4.5.1- with ASPHostPortal.com :: How to Create Barcodes using ASP.NET App

clock February 26, 2014 05:09 by author Kenny

To create barcodes we will use ASP.NET web services. Not only that, we will also create Windows Forms and Console application to request barcode image.

What is The Benefits?

Well, web services provide a major benefit in integrating the software with external applications. With standardized request/response model, any client application that can utilize XML web service can benefit from it.Below is the brief visual representation of the barcode service. The clients do not need to refer to Aspose.BarCode for .NET. They will just send 2 string values (codetext and symbology) and will get the barcode image (byte array) from service.

Barcode Web Service
Now, open Microsoft Visual Studio. Create a new project of type “ASP.NET Web Service Application”. Name the project as “BarCodeService”. Add reference to the following .NET assemblies.

  1. System.Drawing from .NET tab of “Add Reference” dialog box
  2. Aspose.BarCode.

Browse to the location where Aspose.BarCode for .NET is installed and select. Visual Studio adds a default class “Service1” to the Web Service project in Service1.asmx file.
Open it and add the following method to this class.

The web method needs the following two parameters from client:

  1. Codetext
  2. Symbology

These parameters are of String type. The parameters are passed to the BarCodeBuilder class, which then creates the barcode and sends the barcode image in the form of byte array to the client.
This web method can be called by any kind of application that can consume a web service.


Consume Web Service from Windows Forms Application

Open Visual Studio and create a new project of type “Windows Application”. Name the project as “ GetBarCodeWinForms ”. Add reference to the web service by right clicking on “References” and then choosing “Add Service Reference” from the context menu. Type the address of web service or discover it. After getting the correct service, give “BarCodeService” in the Namespace and click on “Ok” button to add the reference.

Design the forms as follows.

It contains the following controls:

  1. Textbox: Input codetext from user
  2. Combobox: Input symbology type from user
  3. Button: Call web service
  4. Picturebox: Display the barcode image

Write the following code on click event of the button.

Run the application, specify some values and click on the “Get Barcode” button. The application will consume the barcode web service and get the barcode image from it. The image will then be displayed on the form as below.

Consume Web Service from a Console Application

Create a new project in Visual Studio and choose “Console Application” in project type. Name the project as “ GetBarCodeConsole ”. Add the reference to the barcode service, just as we gave above in the winforms application.Write the below code in the main() method.

Run the application, it will consume the barcode web service, get barcode image and save the image locally to disk.

Summary

Aspose.BarCode for .NET can easily be used in ASP.NET web services to generate the barcodes and serve the barcode image to various clients.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in