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(); 
}

Friday, 26 August 2016

What is Async & Await in C# .net?

What is Async & Await in C# .net?

If you are familiar with normal ASP.net C# code then this would be easy for you to understand.
just see the below code I'll explain it later (don't go with long red arrow)





In above its a simple asp.net web page code behind where someone click the Button1_Click,and then a callprocess() function get called.after this function we add "Program finish" text in a ListBox1.and increment value of a variable val to 10.

Now how do you think the code need to behave.


STEP 1>STEP 2>STEP3

WHAT you assume normally 

1.int val=0 set in top and declared in last of the button click so val>=10 must fail. right?

2.Listbox add item "Program finish" in last but before it, callprocess() method comes which adding a item "Long Process finish" .so ListBox1 must have LongProcessFinsh in top and Programfinish after that .right?


BUT what realy happens?

Let me tell you everything happen exactly opposite of it.

STEP3(as callprocess() is async other code could not wait for it which has await attach to it)>STEP1>STEP2


In callprocess function the condition "if(val>-0" have value 10 in it already.and ProgramFinish is already added in Listbox1 before LongProcessFinish.

Its because we declare await inside a function (await always do a task(your async kind of task))await LongProcess();


and when you added it you must declare that function with async.

        public async void CallProcess()
        CallProcess();//this is detected as async with calling himself await
        this.ListBox1.Items.Add("Program finish");//they executed without wait
        val += 10;                                                           //they execute without wait


so what basicaly async/await/Task doing 


Async:keyword to declare yes this is a async method

Await:this code will execute but telling other code part dont wait for me I am coming from behind.

Task:like void,we perform here our task which return type is 

Void: Means nothing to return

Task: It will perform one operation, a little similar to void but the difference is there.

Task<T>: Will return a task with a T type parameter. (I hope you are familiar with the concept of T)










Monday, 13 June 2016

Deploy Website In IIS (Asp.net)


Deploy Asp.net Website In IIS Local


1.keep your project  in a folder (eg. D://MyProj/Proj1)
2.go to run
3.type inetmgr
4.on server(LEFT SIDE PANEL)  go to sites>default websites
5.right click on default website and add application
6.give any alias(name for ur project)
7.asp.net application poll must be .net framework 4.0
8.in physical path enter path where your project reside.(eg. D://MyProj/Proj1)

9.'default document' is used to set start_page in case user do not provide any page in url (eg. index.html/defalt.aspx)
10.now go on ur website showing in IIS,right click,manage site and browse.

Below are the solutions for few error which often comes out.


1)HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

DO 1: Enable the Directory Browsing feature in IIS (Recommended)
1.    Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
2.    In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
3.    In the Features view, double-click Directory Browsing.
4.    In the Actions pane, click Enable.
If that does not work for, you might be having different problem than just a Directory listing issue. So follow the below step,

ELSE DO 2: Add a default document
To resolve this problem, follow these steps:
•         Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
•         In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
•         In the Features view, double-click Default Document.
•         In the Actions pane, click Enable.
•         In the File Name box, type the name of the default document, and then click OK.

ELSE DO 3: Enable the Directory Browsing feature in IIS Express

Note This method is for the web developers who experience the issue when they use IIS Express.
Follow these steps:
•         Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt: C:\Program Files\IIS Express
•         Type the following command, and then press Enter:
appcmd set config /section:directoryBrowse /enabled:true


2)ASP.Net IIS7: The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.
CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis -i


Run above command in cmd (RUN AS ADMINISTRATOR)
which will activate asp.net 4.0 like below





3)Website not accessible from other computer in network





1. Open Windows Firewall with Advanced Security ( or run wf.msc)
2. Open Inbound Rules and find World Wide Web Services (HTTP Traffic-In)
3. Right Click on World Wide Web Services (HTTP Traffic-In) and Enable Rule

Print Only Grid View in ASP.net

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