Monday, 11 September 2017

Print Only Grid View in ASP.net

ASP.net How to Print Only GridView
 

<div id="gridviewDiv">
      
   <asp:GridView ID="gridViewToPrint" runat="server" 
                  DataSourceID="SqlDataSource1">
     <Columns>
    <asp:BoundField DataField="CategoryID" 
                    HeaderText="CategoryID"/>
    <asp:BoundField DataField="CategoryName" 
                    HeaderText="CategoryName"/>
    </Columns>
    </asp:GridView>
   </div>
      
   <asp:Button ID="btnPrint" runat="server" 
               Text="Print GridView Data"/>
 
 
 
 
 
 
 
 
 
 
 
 
 
protected void Page_Load(object sender, EventArgs e)
    {
        string printScript =
        @"function PrintGridView()
         {
            var gridInsideDiv = document.getElementById('gridviewDiv');
            var printWindow = window.open('gridview.htm','PrintWindow','letf=0,top=0,width=150,height=300,toolbar=1,scrollbars=1,status=1');
            printWindow.document.write(gridInsideDiv.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();}";
        this.ClientScript.RegisterStartupScript(Page.GetType(), "PrintGridView", printScript.ToString(), true);
        btnPrint.Attributes.Add("onclick", "PrintGridView();");       
    } 

Basic of MVC in ASP.net

Few Basic Things For Starting Up With ASP.NET MVC







Developing a Web Application by Using ASP.NET MVC 2
■ Structure an ASP.NET MVC application.
■ Create custom routes.
■ Create controllers and actions.
■ Create and customize views.


First  Part(UNDERSTANDING BLOG:What is MVC)

DIFFRENCES With ASP.NET
MVC, you write the model, create the views, and code the controllers; thus you have finer
control over how each request is handled and each response is rendered. With ASP.NET MVC,
there is less “hidden” from you (and thus less work done automatically for you).

ASP.net:
ASP.NET application basic architecture , in
which requests are handled by ASP.NET: it calls your page; it executes your events in order;
those events affect the response; and ASP.NET ultimately returns the response.


MVC
MVC application has a different architecture, page processing model, conventions,
and project structure than an ASP.NET web form site.

MVC Components:
These components should be familiar to you as a web developer. A controller is a class; the
model is either made up of custom classes or generated classes that use the Entity Framework
or LINQ to SQL; and the views are ASPX webpages. The following list provides a more detailed
definition of these components:
Controller often called the connection between the model and the view.



Life Cycle of MVC

1.You add routes to this collection inside the Global.asax file’s
RegisterRoutes method (which is called by Application_Start).

2.These routes are added to the
table when your application starts.

3The request is then mapped to a route, and
RouteData and RequestContext objects are created to represent the route and the request, respectively.

4.Processing of the RequestContext object is then passed to classes in the System.Web.Mvc
namespace.

5.The MvcRouteHandler class handles the routing to your MVC controller class. It
creates an instance of MvcHandler to actually call the controller and run its Execute method.


6.Your controller then uses ControllerActionInvoker to determine which action to run based
on the request.

7.Your action method accepts the user input and prepares a response


ROUTES
You add routes to this collection inside the Global.asax file’s
RegisterRoutes method (which is called by Application_Start).You must know both way
1.by direct RouteTable class
2.RegisterRoutes method

Understanding Routing Basics


Your website can respond to both ASP.NET and ASP.NET MVC requests. If no route is found
for a request, the request passes to ASP.NET for processing.



ASP.Net Website/.NET 4.0
 (add a Global.asax file)

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Routing" %>
<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {

        RouteTable.Routes.MapPageRoute("Department", "Department/CITY/{DeptName}", "~/DepartmentwiseEmployees.aspx");
      RouteTable.Routes.MapPageRoute("Department1",        "Dex/{student_name}", "~/Default3.aspx");
       
    }

</script>





MVC Project/.NET4.0
(you will find a file global.asax with this code) 

using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1
{

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
        }
    }
}


//RegisterAllAreas() call to ensure that the area mapping is carried out.
--------------------------------------------------------------------------------------------------------------------

Either write in RegisterRoutes Method as Above or directly Type   RouteTable.Routes.MapPageRoute













Defining Application Areas
AREA 
(just give you logical ready made structure of folder if you want more folder to hold Controller,Views and model)

You can use the default project structure for most websites without having any problems.
However, there are some sites that are very large; keeping all the models, views, and controllers
in this single folder set can be difficult to manage. For such cases, you can define
different MVC project areas in your application.
An area in ASP.NET MVC is a subset of the project structure based on a logical grouping.
Each area contains area-specific models, views, and controllers. The root of the site contains
the sitewide models, views, and controllers. This type of partitioning can make it easier to
manage your application files.
You create an area in ASP.NET MVC by right-clicking the project and choosing Add | Area.
You give each area a name and Visual Studio generates a separate set of folders for storing
the MVC files in your area.





Explanations With Screenshots

You Must Go Through This At A Glance
Quick Check
1. What is the ASP.NET MVC convention for naming controller classes?
2. What is the ASP.NET MVC convention for storing views?
3. What is the ASP.NET MVC convention for naming views?

Quick Check Answers
1. You name your controller classes after entities in your model and add the
Controller suffix, as in EntityController.
2. A view should be stored in a folder with the same name as the controller (minus
the suffix), as in Entity.
3. A view should be named after the action method in the controller, such as
Index.aspx or Create.aspx.

Didn't Undersand?Ok!

1)GLOBAL.ASAX File

















2.PROJECT FILES SCREENSHOT #1




3.PROJECT FILES SCREENSHOT #2




 4.CONTROLLER CLASS






 5.NAMING DEPENDENCIES OF ALL (you can not name anything to Controller and call it with any function name with any name of view, there are some patterns and way to follow)






1. You name your controller classes after entities in your model and add the Controller suffix, as in EntityController.

2. A view should be stored in a folder with the same name as the controller (minus the suffix), as in Entity.

3. A view should be named after the action method in the controller, such as Index.aspx or Create.aspx.














SQL Server Is Too Busy...

SQL Server Is Too Busy...
Quick Tips and tricks to tackle with performance

What?

Today I will guide to resolve the “server too busy” error in asp.net.

Why?

There are few no of reasons to occur this error. By the word itself, we can under this error is occurred when server unable to handle the requests and go busy out while trying to do so.following could be the response which could be the reason of slow down the server.

1.    QUERY RESPONSE:    The database query may take long time to respond.
2.    IIS RESPONSE:             No of free threads not enough to IIS to handle the request
3.    MEMORY RESPONSE:In your code has memory leaks
4.    LOOP RESPONSE:       In your code have infinite loops.
5.    VISITOR RESPONSE:  Server does not have capabilities to handle huge no of visitors.

Solution?

•    If first one is reason for this error, then you may to review your query using SqlProfiler and fix the query to response quickly.
•    If your code has memory leaks or infinite loops, then you have to review your code and have to fix.
•    The second is most important on for this error. But we can fix this case easily with webconfig file.
When you are take look your web config file, there is a tag call httpRuntime like following normally.
<httpRuntime executionTimeout="3600" maxRequestLength="4096" />
 More details about httpRuntime here
To resolve this error with web config, we have to override the following attributes in config.
1.    executionTimeout
2.    maxRequestLength
3.    minFreeThreads
4.    minLocalRequestFreeThreads



executionTimeout
Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.
This time-out applies only if the debug attribute in the compilation element is False. If the debug attribute is True, to help avoiding application shut-down while you are debugging, do not set this time-out to a large value. The default is 110 seconds.
maxRequestLength
Specifies the limit for the input stream buffering threshold, in KB. This limit can be used to prevent denial of service attacks that are caused, for example, by users posting large files to the server. The default is 4096 KB
minFreeThreads
Specifies the minimum number of free threads to allow execution of new requests. ASP.NET keeps the specified number of threads free for requests that require additional threads to complete processing. The default is 8.
minLocalRequestFreeThreads
Specifies the minimum number of free threads that ASP.NET keeps available to allow execution of new local requests. The specified number of threads is reserved for requests that are coming from the local host, in case some requests issue child requests to the local host during processing. This helps to prevent a possible deadlock with recursive reentry into the Web server. The default is 4.
(API definition from MSDN)
Now we have to override values for above attributes. Once override web config file will look followings,
<httpRuntime enableVersionHeader="false" executionTimeout="72000" maxRequestLength="4096" minFreeThreads="72" minLocalRequestFreeThreads="88" useFullyQualifiedRedirectUrl="false" />
 Just override your production web configuration file with above modfied file. Now see your server to able to handle more request than earlier.But your web server does not enough memory or CPU, then you have to upgrade that to support to handle to more request.

Conclusion

In tips I have given solutions to “server too busy” error in asp.net.i hope this is help to you all.

Find Control Under RowCommand

Find Control Under RowCommand


protected void GridViewtemp_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "AddSchedule")
        {
                pnlschedule.Visible = true;
                lblscheduleforItem.Text = e.CommandArgument.ToString();

                GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
                Label lblDate = (Label)row.Cells[0].FindControl("lblName");
                string teamName = lblDate.Text;
                int rowindex = row.RowIndex;
                lblscheduleforItemName.Text = ((Label)GridViewtemp.Rows[rowindex].FindControl("lblName")).Text;

                      
        }
    }

SQL Transaction In C#,ASP.Net

 Transaction In C#,ASP.Net


SqlTransaction transaction;
con.Open();
transaction = con.BeginTransaction();
try
{
for (int i = 0; i < dtTemp.Rows.Count; i++)
{
SqlCommand cmd = new SqlCommand("insert command....", con,transaction);
cmd.ExecuteNonQuery();
}
transaction.Commit();
}

catch (Exception Error)
{


}




In above Part the only thing you have to care about is 


SqlTransaction transaction;
con.Open();
transaction = con.BeginTransaction();
try
{
  SqlCommand cmd = new SqlCommand("insert command....", con,transaction);
  cmd.ExecuteNonQuery();
  transaction.Commit(); //whenever you call commit it means now finaly
                        //all execution will take place else rollback to catch
}
catch
{
 transaction.Rollback(); 
}

Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...