Posts

Showing posts with the label asp.net

Adding control dynamically from Code Behind - Dropdown, Listbox, Checkbox - asp.net

Image
This tutorial/example shows how you can add control dynamically from code behind. This example not only limits to Dropdown, Listbox, and Checkbox controls, but you can use this example for any controls. The only things that you need to understand the process. Step By Step Create one new project name DynamicControls Add One web form or webform using the master page if you use the default template master page. Copy-paste code below respectively. (Note: I'm using the default master page template from VS2010) ASPX code   <h3>         This is Dynamic Control Tutorial     </h3>     <asp:Button ID="Button1" runat="server" Text="Add ListBox To Panel"         onclick="Button1_Click" />     <br />     <asp:Button ID="Button2" runat="server" Text="Add Dropdown To Panel"         onclick="Button2_Click" />     <br />     <asp:Button ID="Button3" runat="server&q

How to specify WhereCondition in Transformation - Nested Control - kentico 8, 7, 6

Image
Before this i wonder how to pass some where condition in transformation repeater. So i ask the kentico guys and he give me a solution which i think i can share to the others. So in your transformation you can specify the <script runat="server"></script> element. This is where you can pass the where condition. Let see the example : Transformation Code <cms:queryrepeater id="repItems" ... DelayedLoading="true" ... /> <script runat="server"> protected void Page_PreRender(object sender, EventArgs e) { queryrepeater.WhereCondition= "NodeAliasPath LIKE '"+(string)Eval("NodeAliasPath")+"'"; queryrepeater.ReloadData(true); } </script> Note : queryrepeater dont have DelayedLoading properties, use DataBindByDefault="false" instead. By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites

Update Panel - Handle async partial-page state with client script

This is a sample script you can put at the master page. So that you dont need to have updatepanel progress every time you add the update panel in you aspx page. Script  <div id="pageUpdating"></div>     <script type="text/javascript">         Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);         function BeginRequestHandler(sender, args) {             //page is begin request, you can put code to lock screen etc.               writePageLoading();         }         Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)         function endRequestHandler(sender, args) {             //page load successfully , end request               RemoveLoading();             if (args.get_error() != undefined && args.get_error().httpStatusCode == '500') {                 //if have error                 var errorMessage = args.get_error().message;                 alert(errorMessage + &qu

What you need to know about Static class

Static Class Properties A static class cannot be instantiated. That means you cannot create an instance of a static class using new operator.  A static class is a sealed class. That means you cannot inherit any class from a static class.  A static class can have static members only. Having non-static member will generate a compiler error. A static class is less resource consuming and faster to compile and execute.  Static Class Example Public static class MyStaticClass  {      Private static int myStaticVariable;      Public static int StaticVariable;      {         Get        {            return myStaticVariable;        }         Set        {            myStaticVariable = value;        }     }    Public static void Function()    {    }  }  Note : The static class can directly called out from the other class for example you create class ClassA , and you can directly type in ClassA to call Function method in class MyStaticClass like this. MyStaticClass.Function(); By Mohd Zul

Nullable Types in .Net C#

Image
Since .NET version 2.0, the new feature introduce which is nullable types.  In the basic programming, how do you assign null to the promitive type such as int, long, and bool. Its is impossible. The following code shows how to define an integer as nullable type and checks if the value of the integer is null or not. Example  /// <summary> /// Nullable types /// </summary> public static void TestNullableTypes() { // Syntax to define nullable types int? counter; counter = 100; if (counter != null) { // Assign null to an integer type counter = null; Console.WriteLine("Counter assigned null."); } else { Console.WriteLine("Counter cannot be assigned null."); Console.ReadLine(); } } If you remove the "?" from int? counter, you will see a warning as following: By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social

How to enable GZip or Deflate on ASP.NET(HTTP Compression)

HTTP compression is a capability that can be built into web servers and web clients to make better use of available bandwidth, and provide greater transmission speeds between both. HTTP data is compressed before it is sent from the server: compliant browsers will announce what methods are supported to the server before downloading the correct format; browsers that do not support compliant compression method will download uncompressed data. Compression as defined in RFC 2616 can be applied to the response data from the server (but not to the request data from the client) The most common compression schemas include gzip and deflate. So how do we gonna achieve this  HTTP Compression on asp.net application.? Here is the Step : Open Global.asax file. Add the method IsCompressionAllowed() to check if compression is allowed. Add code in Application_Start event. Global.asax File void Application_Start(object sender, EventArgs e)         {             //check if request is aspx page.. if java

Basics of .NET Programs and Memory Management

Image
.NET has made a lot of improvements in its core to enhance the performance of an application. It is the first solid-core environment that really connects to all parts of the technology for developers. Inorder to make solid footsteps in the .NET environment, it would be great to know about the basic advantages and also the architecture of the .NET environment that you are going to start working on. The most important infrastructural component of the .NET framework is Common Language Runtime (CLR) . The code that you write inside the framework is called the managed code , which benefits from cross-language integration, cross-language exception handling, enhanced security,  versioning, and easy deployment support. Every component in a managed environment conveys some specific rule sets. When you write your code in a managed environment, the code gets compiled into the common intermediate language (CIL) . This language remains constant or equivalent to a code that might be compiled from an

Control Webpart Visible/Enable using macro in Kentico

Image
Simple post just to show how you can enable or visible the webpart in certain page. This is basically to avoid using many template. You can use only one template that have many webpart, and you can control visible/enable it using macro. Macro Code {% if(NodeAlias == "Search") {    return true; } else {  return false; } %} By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

How to track download file analytics in Kentico 7

Let say you create one Document Type in Kentico CMS, and inside the document type got one field for attachment. So you want to track/count how many time the document download using Web Analytic feature in Kentico. First of all you need to enable the web analytic feature in  Kentico. Follow this link to read more about web analytic in kentico. Here is the solution to track/count download file for a DocumentType Field. A bit of customization is required to track all the downloaded files. The problem is that only CMS.File document type downloads are tracked by default. However, you can change that by going to the file: \CMSPages\GetFile.aspx.cs Within this file, around line 1268 or Find method LogEvent there is the following condition: if (IsLiveSite && (file.FileNode != null) && (file.FileNode.NodeClassName.ToLower() == "cms.file")) You have to alter it to the following one so all files are logged, not only files attached to a CMS.File document: if (IsLiveSite

Create Navigation Using Kentico 7 Repeater Webpart

Image
Kentico CMS for ASP.NET empowers marketers and developers in creating websites without limits. It's the ultimate solution for your website, store, community and on-line marketing initiatives. Today i want to show how you can use Repeater Webpart to create one Navigation. On this post i will more focus on the Transformation . Let say this is your navigation html code : Navigation Html Code <ul class="megamenu">    <li>     <a href="#_" class="megamenu_drop">LEVEL ONE</a>     <div class="dropdown_3columns dropdown_container">       <ul class="dropdown_flyout">         <li class="dropdown_parent">           <a href="#_">LEVEL TWO</a>           <ul class="dropdown_flyout_level">             <li>               <a href="#_">LEVEL THREE</a>             </li>           </ul>         </li>       </ul>

How to splitting huge ViewState size

When the ViewState in your page becomes very large it can be a problem since some firewalls and proxies will prevent access to pages containing huge ViewState sizes. For this purpose ASP.NET introduces the ViewState Chunking mechanism. So ASP.NET enables splitting of the ViewState's single hidden field into several using the MaxPageStateFieldLength property in the web.config section. When the MaxPageStateFieldLength property is set to a positive number, the view state sent to the client browser is broken into multiple hidden fields. Setting the MaxPageStateFieldLength property to a negative number (the default) indicates that the view-state field should not be separated into chunks. Setting the MaxPageStateFieldLength to a small number may result in poor performance. Sample ViewState before: <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"value="/wEPDwUKLTk2Njk3OTQxNg9kFgICAw9kFgICCQ88KwANAGQYAQUJR3Jp ZFZpZXcxD2dk4sjERFfnDXV/hMFGAL10HQU

How to disable asp.net version and server information on HTTP Headers

Image
Scenario: We identified that the target web server is disclosing the ASP.NET version in its HTTP response. This information might help an attacker gain a greater understanding of the systems in use and potentially develop further attacks targeted at the specific version of ASP.NET. Impact: An attacker might use the disclosed information to harvest specific security vulnerabilities for the version identified. Solution Disable the asp.net version and server information on http headers. Open the web.config file and add this code in the web.config file : <system.webServer>     <httpProtocol>         <customHeaders>             <remove name="Server" />             <remove name="X-AspNet-Version" />             <remove name="X-AspNetMvc-Version" />             <remove name="X-Powered-By" />                                </customHeaders>            </httpProtocol>   </system.webServer> You al

How to disable httpOnlyCookies - asp.net

Scenario HTTP only cookies cannot be read by client-side script therefore marking a cookie as HTTP only can provide an additional layer of protection against cross-site script attack. Impact: During Cross-Site scripting attack and attacker might easily access cookies and hijack the victim’s session. Solution You can disable the httpOnlyCookies on the web.config file. Open the web.config file and add the configuration on the httpCookies element like example below : <system.web> : : <httpCookies httpOnlyCookies="false" requireSSL="false" domain="" /> : :  </system.web> By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Store and retrieve image from database MSSQL - asp.net

This is a example to upload image and store into database. The example also show how to retrieve image from database. Note : Assume the web page have their own master page SQL Create Table SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[imageTest](     [ID] [int] IDENTITY(1,1) NOT NULL,     [Image] [image] NULL,  CONSTRAINT [PK_imageTest] PRIMARY KEY CLUSTERED (     [ID] ASC )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ASPX page Code     <asp:Label ID="Label1" runat="server" Text="Image Upload :"></asp:Label>     <asp:FileUpload ID="FileUpload1" runat="server" />     <br />     <asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />     <br />     <br />     <asp:Panel ID="

Example Upload File - ASP.NET

This is example of upload file using asp.net. Html   <fieldset style="width: 804px" align="center">         <legend><em>Using the FileUpload Control</em>&nbsp;</legend>         <div align="left" style="text-align: center">             <form id="form1" runat="server">                 <div>                     <table style="width: 90%">                         <tr>                             <td colspan="2">                                 <br />                                 <asp:Label ID="LSuccessMssg" runat="server"></asp:Label>                                 <asp:FileUpload ID="FileUpload1" runat="server" /><asp:Button ID="buttonUpload" runat="server"                                     Text="Upload" OnClick="buttonUpload_Click1&quo

MVC - URL Routing

Image
   The segments in an examle URL The first segment contains the word Admin , and the second segment contains the word Index . To the human eye, it is obvious that the first segment relates to the controller and the second segment relates to the action. But, of course, we need to express this relationship in a way that the routing system can understand. Here is a URL pattern that does this: {controller}/{action} or {controller}/{action}/id or {controller}/{action}/id?querystring2=&querystring3=  Note : id, querystring2, and querystring 3 is a parameter in the controller . When processing an incoming request, the job of the routing system is to match the URL that has been requested to a pattern and extract values from the URL for the segment variables defined in the pattern. The segment variables are expressed using braces (the { and } characters). The example pattern has two segment variables with the names controller and action , and so the value of the controller segment variable

Understanding the ASP.NET MVC Framework Pattern

Image
In high-level terms, the MVC pattern means that an MVC application will be split into at least three pieces: Models , which contain or represent the data that users work with. These can be simple view models, which just represent data being transferred between views and controllers; or they can be domain models, which contain the data in a business domain as well as the operations, transformations, and rules for manipulating that data. Views , which are used to render some part of the model as a user interface. Controllers , which process incoming requests, perform operations on the model,and select views to render to the user. Models are the definition of the universe your application works in. In a banking application, for example, the model represents everything in the bank that the application supports, such as accounts, the general ledger, and credit limits for customers as well as the operations that can be used to manipulate the data in the model, such as depositing funds and ma

MVC 4 - Example sending email - WebMail

This is a example of sending email snippet code in Razor Editor. Sample Sending Email - Razor @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Thanks</title> </head> <body> @{ try { WebMail.SmtpServer = "smtp.example.com"; WebMail.SmtpPort = 587; WebMail.EnableSsl = true; WebMail.UserName = "mySmtpUsername"; WebMail.Password = "mySmtpPassword"; WebMail.From = "rsvps@example.com"; WebMail.Send("party-host@example.com", "RSVP Notification", "Message Send will be here"); }  catch (Exception)  { @:<b>Sorry - we couldn't send the email to confirm your RSVP.</b> } } <div> </div> </body> </html> By Mohd Zulkamal NO

MVC 4 - Adding Validation in a form

Image
This is a example of adding a validation in MVC form. Please refer to this post for reference of this example. Adding error message and validation rule GuestResponse.cs using System; using System.Collections.Generic; using System.Web; using System.ComponentModel.DataAnnotations; namespace MyFirstMVCApp.Models {     public class GuestResponse     {         [Required(ErrorMessage = "Please enter your name")]         public string Name { get; set; }         [Required(ErrorMessage = "Please enter your email address")]         [RegularExpression(".+\\@.+\\..+",         ErrorMessage = "Please enter a valid email address")]         public string Email { get; set; }         [Required(ErrorMessage = "Please enter your phone number")]         public string Phone { get; set; }         [Required(ErrorMessage = "Please specify whether you'll attend")]         public bool? WillAttend { get; set; }     } } HomeController.cs         [H

MVC 4 - Creating simple Data-Entry Application

This example will show how to create simple data entry form in MVC4 asp.net. Step By Step Creating Data Entry Application File >> New Project Choose ASP.NET MVC4 Web Application . (If you dont have MVC 4, Install it here ) On Project Template , choose Empty if you want to start from zero or choose Internet Application to start developement with default template. Choose View engine Razor. Click OK button  Create HomeController.cs under Controller Folder. Create GuestResponse.cs Model Create RsvpForm , Thanks , and Index View under View >> Home folder. See the file code example below. HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MyFirstMVCApp.Models; namespace MyFirstMVCApp.Controllers {     public class HomeController : Controller     {         //         // GET: /Home/         public ViewResult Index()         {             return View();         }         public ViewResult RsvpForm