google

Newest Post

Showing posts with label ASP.NET. Show all posts
Showing posts with label ASP.NET. Show all posts

Convert base64 into Image, Resize the image and again convert it into base64

| Saturday, March 5, 2016
Read more »
Convert base64 into Image, Resize the image and again convert it into base64

Use Following Code:

                       byte[] bytes = (byte[])row["Picture"];

                        Image image;

                       //Convert byte[] into image
                        using (MemoryStream ms = new MemoryStream(bytes))
                        {
                            image = Image.FromStream(ms);
                        }

                        // Resize the image
                        Bitmap b = new Bitmap(200, 200);
                        Graphics g = Graphics.FromImage((Image)b);
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                        g.DrawImage(image, 0, 0, 200, 200);
                        g.Dispose();
                        image = (Image)b;

                        using (MemoryStream ms = new MemoryStream())
                        {
                            // Convert Image to byte[]
                            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                            byte[] imageBytes = ms.ToArray();

                            // Convert byte[] to Base64 String
                            string base64String = Convert.ToBase64String(imageBytes);
                            obj.StudentPicture = base64String;
                        }

Convert base64 into Image, Resize the image and again convert it into base64

Posted by : Stranger
Date :Saturday, March 5, 2016
With 0comments

Code to export the Grid View/Data Grid data into Excel File.

| Friday, February 13, 2015
Read more »
 protected void btnExportToExcel_Click(object sender, EventArgs e)  
   {  
     try  
     {  
       DataTable dt = student.GetDetails("B.Tech").Tables[0];  
       DataGrid GridView1 = new DataGrid();  
       GridView1.DataSource = dt;  
       GridView1.DataBind();  
       Response.Clear();  
       Response.Buffer = true;  
       Response.AddHeader("content-disposition", string.Format("attachment; filename=StudentsBTech.xls"));  
       Response.Charset = "";  
       Response.ContentType = "application/vnd.ms-excel";  
       StringWriter sw = new StringWriter();  
       HtmlTextWriter htw = new HtmlTextWriter(sw);  
       GridView1.GridLines = GridLines.Both;  
       GridView1.AllowPaging = false;  
       GridView1.RenderControl(htw);  
       Response.Output.Write(sw.ToString());  
       GridView1.DataBind();  
       Response.Flush();  
     }  
     catch (Exception ex)  
     {  
     }  
     finally { Response.End(); }  
   }  
   public override void VerifyRenderingInServerForm(Control control)  
   { }  

Code to export the Grid View/Data Grid data into Excel File.

Posted by : Stranger
Date :Friday, February 13, 2015
With 0comments

Could not add reference to "System.Net.Http.Formatting" namespace in WPF web api client project

| Friday, December 12, 2014
Read more »
For adding the reference in your web api client

1. Right click on "References" in the solution.
2. Following window will open.


3. Select location "Extension" as shown above and check "System.Net.Http.Formatting" namespace
4. and DONE!!!

Display multiple markers on Google World Map in asp.net website with locations from database

| Wednesday, November 12, 2014
Read more »
In Google Maps in asp.net website with dynamic addresses from database. , I explained how to display the address of a location on the google world map from the database. This article displayed only one address on the map. But in this article, I will explain and provide the sample code to display markers for multiple locations on google map from the database. This feature can be used to display multiple clients or hotels etc in an area on the google world map.

First of all, Add following javascript in the head section of the page to access the google maps API.

 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>  

Add following javascript code in the head section of the page to access the google api functions to display the map on the page.

  var geocoder;  
     var map;  
     var infoWindow = new google.maps.InfoWindow;  
     function initialize() {  
       geocoder = new google.maps.Geocoder();  
       var latlng = new google.maps.LatLng(-34.397, 150.644);  
       var mapOptions = {  
         zoom: 2,  
         center: latlng,  
         mapTypeId: google.maps.MapTypeId.ROADMAP  
       }  
       map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);  
     }  

geocoder - initializes the Geocoder class of google map API
map - displays the map in the div added on the page for displaying map along with various map options like zoom, maptype etc.
infoWindow - displays the small tooltip like window on google map when a marker is clicked.

To display multiple markers, either an xml file generated from the database can be used or an xml string can be generated from the database. Here I am using an xml string from the database which contains the name of the person, its address and link to check his/her profile.

Following html is added on the page to display the map on the webpage.
  <div id="main_table">  
     <div id="main_wrap">  
       <asp:HiddenField ID="hdnAddress" runat="server" />  
       <div id="map_canvas" style="width: 900px; height: 600px;"></div>  
     </div>  
   </div>  

The code behind file will contain code to call the javascript methods and generate xml string. Write the following code in Page_Load event
  if (!IsPostBack)  
       {  
         ClientScript.RegisterStartupScript(GetType(), "show", "initialize();", true);  
         string xmlAddresses = @"<?xml version='1.0' encoding='utf-8' ?>";  
         xmlAddresses = xmlAddresses + @"<markers>";  
         DataTable dt = person.GetFellowsForLocations();  
         if (dt.Rows.Count > 0)  
         {  
           foreach (DataRow row in dt.Rows)  
           {  
             encrypt = new EncryptDecrypt.MyEncryptor(string.Empty);  
             string queryStr = encrypt.Encrypt(Convert.ToString(row["Id"]));  
             xmlAddresses = xmlAddresses + @"<marker address='" + Convert.ToString(row["FellowshipCountry"]).Trim() + "' name='" + Convert.ToString(row["FirstName"]) + " " + Convert.ToString(row["LastName"]) + "' url='fellowdetail.aspx?id=" + queryStr + "'></marker>";  
           }  
         }  
         xmlAddresses = xmlAddresses + @"</markers>";  
         hdnAddress.Value = xmlAddresses;  
         ClientScript.RegisterStartupScript(GetType(), "show1", "codeAddress();", true);  
       }  

Following script is used to display the markers on the google world map
 function codeAddress() {  
       var locations = document.getElementById('<%= hdnAddress.ClientID %>').value;  
       locations = StringToXML(locations);  
       var addresses = locations.documentElement.getElementsByTagName("marker");  
       for (var i = 0; i < addresses.length; i++) {  
         var address = "";  
         var name = addresses[i].getAttribute("name");  
         var url = addresses[i].getAttribute("url");  
         address = addresses[i].getAttribute("address");  
         var html = name + "<br/><a href='" + url + "'>View Profile</a>";  
         (function (html) {  
           geocoder.geocode({ 'address': address },  
             function (results, status) {  
               if (status == google.maps.GeocoderStatus.OK) {  
                 map.setCenter(results[0].geometry.location);  
                 var marker = new google.maps.Marker({  
                   map: map,  
                   position: results[0].geometry.location  
                 });  
                 bindInfoWindow(marker, map, infoWindow, html);  
               } else {  
                 alert("Geocode was not successful for the following reason: " + status);  
               }  
             });  
         })(html);  
       }  
     }  

Add following javascript method to convert xml string into xml type data.

 function StringToXML(oString) {  
       //code for IE  
       if (window.ActiveXObject) {  
         var oXML = new ActiveXObject("Microsoft.XMLDOM"); oXML.loadXML(oString);  
         return oXML;  
       }  
         // code for Chrome, Safari, Firefox, Opera, etc.  
       else {  
         return (new DOMParser()).parseFromString(oString, "text/xml");  
       }  
     }  

Add following javascript function to display the tooltip like window when a marker is clicked.

  function bindInfoWindow(marker, map, infoWindow, html) {  
         google.maps.event.addListener(marker, 'click', function () {  
         infoWindow.setContent(html);  
         infoWindow.open(map, marker);  
       });  
     }  

The output in the browser will be

Size of the map and canvas can be changed as per the requirement. Also the zoom levels of the map can be altered in map options while initializing.

Display multiple markers on Google World Map in asp.net website with locations from database

Posted by : Stranger
Date :Wednesday, November 12, 2014
With 3comments
Tag :

Integrating PushSharp In the WCF Restful Web Service to display Push Notifications in Apple, Android and Windows devices

| Monday, September 29, 2014
Read more »
Hello Folks, Today I will demonstrate the method of integrating the PushSharp library in WCF Restful Web Service to send the Push Notifications to Apple, Android and Windows devices.


This library and its documentation is available on the GitHub at following link

Redth/PushSharp


Create a new WCF web service in the Visual Studio(Here I am using Visual Studio 2012). After creating the Web Service, Go to Tools-> NuGet Package Manager -> Manage NuGet Packages for Solution as shown in following image.




In the Package Manager, Search "PushSharp" 


After installing PushSharp NuGet Package, following dlls will be added in the bin folder of the solution. 




Next are the lines of the code which are used to send the notifications from the web service. Please consider following is the minimalist code required to send notifications to devices. For additional functionality, please go through the samples given in the GitHub library of PushSharp.

For Sending Push Notifications to the Android device.

 public void SendAdnoirdPush(string APIKey, string DeviceID, string Message)  
   {  
     var push = new PushBroker();  
     push.RegisterGcmService(new GcmPushChannelSettings(APIKey));  
     push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(DeviceID)  
             .WithJson("{\"alert\":\"" + Message + "\",\"badge\":7,\"sound\":\"sound.caf\"}"));  
   }  

APIKey of the App can be obtained from the Google Developer Console.
DeviceId of the device using the App.
Message to be displayed in the Notification.


For Sending Push Notifications to the iOS device.

 public void SendiOSPush(string DeviceID, string Message, string sound)  
   {  
     var push = new PushBroker();  
     var appleCert = File.ReadAllBytes(new DirectoryInfo(HostingEnvironment.ApplicationPhysicalPath) + "/pushNotificatio.p12");  
     push.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, "CertificatePassword"));  
     push.QueueNotification(new AppleNotification()  
                   .ForDeviceToken(DeviceID)  
                   .WithAlert(Message)  
                   .WithBadge(7)  
       .WithSound(sound));  
     //.WithSound("sound.caf")); //default  
   }  

DeviceId of the device using the App.
Message to be displayed in the Notification
sound to be played with Notification

For implementing the iOS Notifications, a signed certificate is required to be generated from the Developer Console. That certificate is copied in the system and Path is given as in the method above. 
Please be careful while mapping the path of the certificate. The certificate is different for sandbox and production
RegisterAppleService requires the certificate password. 

For Sending Push Notifications to the Windows phone.

 public void SendWindowsPhonePush(string ChannelUri, string pageName, string Header, string Message)  
   {  
     var push = new PushBroker();  
     push.RegisterWindowsPhoneService();  
     push.QueueNotification(new WindowsPhoneToastNotification()  
     .ForEndpointUri(new Uri(ChannelUri))  
     .ForOSVersion(WindowsPhoneDeviceOSVersion.Eight)  
     .WithBatchingInterval(BatchingInterval.Immediate)  
     .WithNavigatePath("/" + pageName)  
     .WithText1(Header)  
     .WithText2(Message));  
   }  

ChannelUri is the unique identifier for each device using the App
pageName to navigate to when notification is clicked
Header to be displayed in the Notification Header
Message to be displayed in the Notification Message


and voila!!!! DONE

Above methods can also be combined into one method to send notification to all types of devices., also If notifications are to be sent to multiple devices of same OS, then a "for" loop can be traversed as per the requirement for each method.

Convert DataSet or DataTable into JSON in C#

| Tuesday, June 10, 2014
Read more »
 public string ConvertToJSON(DataSet ds)  
 {  
 System.Web.Script.Serialization.JavaScriptSerializer serializer = 
new System.Web.Script.Serialization.JavaScriptSerializer();  
     List<Dictionary<string, object>> rows = 

new List<Dictionary<string, object>>();  
     Dictionary<string, object> row = null;  
     foreach (DataRow dr in ds.Tables[0].Rows)  
     {  
       row = new Dictionary<string, object>();  
       foreach (DataColumn col in ds.Tables[0].Columns)  
       {  
         row.Add(col.ColumnName.Trim(), dr[col]);  
       }  
       rows.Add(row);  
     }  
     return serializer.Serialize(rows);  
 }  

Convert DataSet or DataTable into JSON in C#

Posted by : Stranger
Date :Tuesday, June 10, 2014
With 0comments

Update the .edmx file when the database changes

| Saturday, May 17, 2014
Read more »
To update the .edmx file when the database changes

  1. In the Model Browser, right-click the .edmx file and select Update Model from Database.
  2. The Update Model Wizard starts. If there is no database connection specified, the Choose Your Database Connection dialog box appears. Otherwise, the Choose Your Database Objects dialog box appears. 
  3. If the Choose Your Database Connection dialog box appears, specify a database connection. Otherwise, go to the next step.
  4. For details about specifying a connection, see Choose Your Data Connection Dialog Box (Entity Data Model Wizard). When you have specified the connection, click Next to display the Choose Your Database Objects dialog box.
  5. Click the Add tab.
    Nodes for tables, views, and stored procedures are displayed. If any objects have been added to the database (or were not included in the previous storage model), you can expand the corresponding node to view the objects that are available to add to the conceptual model.
  6.  If an object has been deleted from the conceptual model but has not also been deleted from the storage model, the object will not be available to add to the conceptual model.
  7. Expand the Tables, Views, and Stored Procedures nodes, and check the objects you want to add to the .edmx file.
  8. Click the Refresh tab.
    Nodes for tables, views, and stored procedures that are included in the existing storage model are displayed. Any changes that have been made to these database objects will be reflected in the updated storage model. Changes to the conceptual model are made when columns are added to a table or view.
  9. Click the Delete tab.
    Nodes for tables, views, and stored procedures are displayed. If an object has been deleted from the database and was included in the previous storage model, you can expand the corresponding node. The objects in these nodes will be deleted from the updated model.
    Click Finish to update the .edmx file with the database changes.

Reference - MSDN

Update the .edmx file when the database changes

Posted by : Stranger
Date :Saturday, May 17, 2014
With 0comments

How to apply RowFilter on DataView

| Friday, May 9, 2014
Read more »
Following code can be used to apply filter on the DataView

 DataSet ds = new DataSet();  
 ds= GetData();  
 DataView dv = ds.Tables[0].DefaultView;  
 dv.RowFilter = "SrNo='" + txtSNo.Text.Trim() + "'";   


LIKE, AND , OR operators can also be used in the RowFilter of Dataview.

To access the filtered records, each DataRowView of the DataView

 foreach (DataRowView drv in dv)  
       {  
         currentName = Convert.ToString(drv["Name"]);  
       }  



How to apply RowFilter on DataView

Posted by : Stranger
Date :Friday, May 9, 2014
With 0comments

Unable to find the requested .Net Framework Data Provider. It may not be installed.

| Thursday, April 10, 2014
Read more »
Above error can be caused by if the "Provider" given in "SqlDataSource" or any other data source control is not updated.

This error can be resolved either by updating the Provider details in connection string property of web.config file or you simply remove the

 ProviderName="<%$ ConnectionStrings:DbConnectionString.ProviderName %>"  


from SqlDataSource control or any other data source control.

Convert byte[] array into base64 string in C#.NET or ASP.NET

| Wednesday, April 2, 2014
Read more »
Following is the code which can be used to convert an Image data from the SQL Server Database Image type column. SQL Server returns image column in the format of byte array i.e byte[].

  if (ds.Tables.Count > 0)  
       {  
         if (ds.Tables[0].Rows.Count > 0)  
         {  
           string MyImage = Convert.ToBase64String((byte[]) ds.Tables[0].Rows[0]["MySnap"]);  
          }  
       }  

We can retrieve the image column in DataSet or using the DataReader and then use Convert.ToBase64String() method to convert it into base64 string.

Above code can also be used for WCF service methods while sending data from database to mobile devices or some other purpose.

Convert byte[] array into base64 string in C#.NET or ASP.NET

Posted by : Stranger
Date :Wednesday, April 2, 2014
With 0comments

ScriptManager.RegisterStartupScript using JavaScriptSerializer - To display the Alert or Message Box from Code behind

| Thursday, March 13, 2014
Read more »
While registering a message using the javascript code in RegisterStartupScript, message might contain some escape characters like ' or " this will definitely break the javascript. Hence we need to encode it, for example using JavaScriptSerializer as follows.



  string message = new JavaScriptSerializer().Serialize(ex.Message.ToString());  
  string myScript = String.Format("alert('{0}');", msg);  
  ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);  




TextBoxMode Enumeration or TextMode attribute of TextBox

| Thursday, February 20, 2014
Read more »
The TextBoxMode enum specifies the behavior mode of the ASP.NET web control textbox. This is specified in the TextMode attribute of TextBox control.

 <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>  

"TextMode" attribute or "TextBoxMode" enum represents the different display options of the TextBox.

  • SingleLine - displays the textbox in a single row. If text exceeds the physical size of the control, it automatically adds scroll to the textbox
  • MultiLine - displays the height and length of the textbox based upon the Rows and Columns of the textbox. It allows text entry in multiple lines. Data entered in multiline textbox can be wrapped if Wrap property is set to true.
  • Password - similar to SingleLine except the all characters entered in Textbox are masked and not saved in viewstate.
There are other options also for TextMode attribute of textbox control like Email, Number, Date, DateTime etc. but they correspond to the type attribute of input element in the HTML5 hence not supported in other versions of html.

TextBoxMode Enumeration or TextMode attribute of TextBox

Posted by : Stranger
Date :Thursday, February 20, 2014
With 0comments

How to use Built-in Content Filters of RadEditor to enable Absolute URLs

| Thursday, February 6, 2014
Read more »
RadEditor provides feature to upload images, documents, videos etc along with the content. The default path for uploading and viewing these attachments is the path relative to the website.

To make the path absolute for certain situations, add ContentFilters="MakeUrlsAbsolute" attribute to the RadEditor as follows.


  <telerik:RadEditor runat="server" ID="RadEditor1" SkinID="DefaultSetOfTools" Height="400px" ContentFilters="MakeUrlsAbsolute"  
         Width="100%" CssClass="addeditor">  
         <Content>  
         </Content>  
         <ImageManager ViewPaths="~/Upload" UploadPaths="~/Upload" DeletePaths="~/Upload"></ImageManager>  
         <DocumentManager MaxUploadFileSize='2100000' ViewPaths="~/Upload" UploadPaths="~/Upload" DeletePaths="~/Upload"></DocumentManager>  
       </telerik:RadEditor>  

It will make all src attributes in the editor content to have absolute URLs

How to use Built-in Content Filters of RadEditor to enable Absolute URLs

Posted by : Stranger
Date :Thursday, February 6, 2014
With 0comments

Attaching master page dynamically to a conetnt page

| Tuesday, January 28, 2014
Read more »

As the master page and content page are merged during the initialization stage of page processing, a master page must be assigned before then.
 protected void Page_PreInit(object sender, EventArgs e)  
   {  
     try  
     {  
       if (AdminPages)  
         this.Page.MasterPageFile = "~/Admin.master";  
       else  
         this.Page.MasterPageFile = "~/General.master";  
     }  
     catch (Exception ex)  
     {  
     }  
   }  

The MasterPageFile property can be set only in the PreInit event; attempting to set the MasterPageFile property after the PreInit event will throw an InvalidOperationException exception. If the MasterPageFile property is not valid, an exception of type HttpException is thrown later in the page life cycle, but no exception is thrown when the property is set in the PreInit event.

Attaching master page dynamically to a conetnt page

Posted by : Stranger
Date :Tuesday, January 28, 2014
With 0comments

How to - Populate RadEditor's Apply CSS Class dropdown with custom styles.

|
Read more »
Populate RadEditor's Apply CSS Class dropdown with custom styles.


 <telerik:RadEditor runat="server" ID="RadEditor1" SkinID="DefaultSetOfTools" Height="400px"  
 Width="100%" >  
 <CssFiles>  
    <telerik:EditorCssFile Value="mystyle.css" />  
 </CssFiles>   
 </telerik:RadEditor>  

Comparison between ASP.NET MVC Web Application and ASP.NET website

|
Read more »
ASP.NET Web Forms ASP.NET MVC
ASP.NET WebForms model follows a Page Life cycle. No Page Life cycle like WebForms. Request cycle is simple in ASP.NET MVC model.
As every page (.aspx) has its own controller (code behind i.e. aspx.cs/.vb file), so both are tightly coupled.Hence there is no separation of concerns. View and Controller are neatly separate. Very clean separation of concerns.
Because of this coupled behavior, automated testing is really difficult. Test driven development is quite simple using this approach.Testability is a key feature in ASP.NET MVC. 
ASP.NET web forms maintain state throughout the website.In order to achieve this stateful behavior, viewstate is used. ASP.NET MVC approach is stateless as that of the web. So there is no concept of viewstate.
Statefulness has a lots of problem for web environment in case of excessively large viewstate. Large viewstate means increase in page size. As controller and view are not dependent and also no viewstate concept in ASP.NET MVC, so output is very clean.
ASP.NET Web Forms use Page controller pattern approach for rendering layout. In this approach, every page has its own controller, i.e., code-behind file that processes the request. ASP.NET MVC uses Front Controller approach. That approach means a common controller for all pages processes the requests.
Along with statefulness, Microsoft tries to introduce server-side controls as in Windows applications. Purpose was to provide somehow an abstraction to the details of HTML. In ASP.NET Web Forms, minimal knowledge of HTML, JavaScript and CSS is required. In MVC, detailed knowledge of HTML, JavaScript and CSS is required.
The above abstraction was good but provides limited control over HTML, JavaScript and CSS which is necessary in many cases. Full control over HTML, JavaScript and CSS.
With a lots of control libraries availability and limited knowledge of other related technologies, ASP.NET WebForms is RAD(Rapid Application Development) approach. It's a step back. For developers decrease in productivity.
It’s good for small scale applications with limited team size. It’s better as well as recommended approach for large-scale applications where different teams are working together.

What is the need of Master Pages?

| Saturday, January 18, 2014
Read more »
In Web site development with ASP.NET, the master page is a feature that enables you to define common structure and interface markup elements for your Web site, including headers, footers, style definitions, or navigation bars. The master page can be shared by any of the pages in your Web site, called the Content Page, and removes need to duplicate code for shared elements within your Web site.

Before Master Pages
Every website contains a common layout for most of the pages. Earlier before master pages,layout code was written on every page, which led to code redundancy and it was difficult to maintain also.

The common layout problem can be handled in two ways 
1. Using Master Pages
2. Using User Controls

User controls have few disadvantages
1. Code of User control is compiled again and again every time page loads.
2. Any change to the public environment of the User control needs to update code on the linked pages

Another option is Master Pages.A Master page is a feature that enables you to define common structure and interface markup elements for your Web site, including headers, footers, style definitions, or navigation bars. The master page can be shared by any of the pages in your Web site, called the Content Page, and removes need to duplicate code for shared elements within your Web site.

A master page is similar to an ordinary ASP.NET page except for the top @Master directive and the presence of one or more ContentPlaceHolder server controls. A ContentPlaceHolder
control defines a region in the master page that can be customized in a derived page. ContentPlaceHolder acts as container which holds controls/items defined in the derived pages.

 <asp:ContentPlaceHolder runat="server" ID="mainContent" />  

In the derived pages, server control is used to provide actual content to ContentPlaceHolders of Master Page. The link between placeholders and content is
established through the Content place holder ID.

 <asp:Content runat="server" contentplaceholderID="mainContent">  
 </asp:Content>  

1. In a master page, there can be multiple content place holders.
2. Content page is used to fill the content in their master pages and it should only contain <asp:Content> server control. Everything (like different content) should be
defined in that only.
3. For a given Content place holder, default content can be defined in the master page itself. If it has not been overridden in Content page, the content defined in the master will be
displayed.
4. A placeholder can't be bound to more than one content region in a single content page. If you have multiple <asp:Content> server tags in a content page, each must point to a
distinct placeholder in the master.
5. A ContentPlaceHolder control can be used only in a master page. Content placeholders are not valid on regular ASP.NET pages. If such a control is found in an ordinary Web
page, a parser error occurs.
6. The MasterPage class, in turn, inherits UserControl. So, at the end of the day, a master page is treated as a special kind of ASP.NET user control.


Attributes of @Master Directive

1. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.


2. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same master file or in code behind. The default value is True.


3. CodeFile: Specifies the code-behind file with which the MasterPage is associated.


4. Title: Set the MasterPage Title.


5. MasterPageFile: Specifies the location of the MasterPage file to be used with the current MasterPage. This is used for Nested Master Pages.


6. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.


7. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.

Language used in master page and content pages can be different.

Master page can be attached to content page in different ways
1. Page Level
2. Folder Level
3. Application Level

Since Master and Content pages are interdependent, either of the page changes, dynamic assembly needs to be re-created.

When the user requests a page, first it checks whether master page exists or not. If there is any master page, then first master page will be compiled. If the folder consists of multiple master pages, all of them will be compiled at the same time. So when the user access any page for the first, page loading may take a little bit time for compiled, from the next time onwards, it won’t take much time, as master pages are already compiled and cached. When compared to User controls, this is an advantage for master pages as User Controls need compilation every time.

Master pages can be nested. There is no limitation on nesting levels. Nested master pages will have ContentPlaceHolder as well as @MasterPageFile directive.

What is the need of Master Pages?

Posted by : Stranger
Date :Saturday, January 18, 2014
With 0comments

How to use ASP.NET Custom Validator on client side

| Friday, April 5, 2013
Read more »
Knowledge Bank: ASP.NET Custom Validator: Asp.Net Custom validator allows us to validate the controls on page on client side as well as server side, But mainly the validation is done...

How to use ASP.NET Custom Validator on client side

Posted by : Stranger
Date :Friday, April 5, 2013
With 0comments
Tag :

Web response to display data from another website

| Wednesday, March 20, 2013
Read more »
Data from another website can be displayed in our own website using simple "WebRequest" and "WebResponse".WebRequest uses URL of the another website which can be passed hard coded or dynamically.

Add a Label control on the webpage.

 <asp:Content ID="Content2" ContentPlaceHolderID="generalContent" runat="Server">  
   <asp:Label ID="lblDisplay" runat="server">   
   </asp:Label>  
 </asp:Content>  

Add following code in Page_Load or any other event like button click etc.

 WebRequest wReq = WebRequest.Create("https://www.youtube.com/watch?v=CGu8W4cFlUw");  
       WebResponse mRes = wReq.GetResponse();  
       StreamReader sr = new StreamReader(mRes.GetResponseStream());  
       string sHTML = sr.ReadToEnd();  
       sr.Close();  
       mRes.Close();  
       if (sHTML != string.Empty && sHTML != null)  
       {  
         lblDisplay.Text = sHTML;  
       }  

Add required namespaces in the cs file

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

and That's it.

Enjoy!!!

The output in the browser will be


Web response to display data from another website

Posted by : Stranger
Date :Wednesday, March 20, 2013
With 1 comments:
Tag : ,

LINQ Tutorial-Adding, Updating and Deleting Data

| Monday, March 11, 2013
Read more »

LINQ Tutorial-Adding, Updating and Deleting Data

Posted by : Stranger
Date :Monday, March 11, 2013
With 3comments
Tag :
Prev
▲Top▲