MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Monday, 30 October 2017

How to Read and display HTML file in Windows form application

07:55:00 Posted by raviteja swayampu , No comments
In this tutorial Raviteja Swayampu explained about how to read and display HTML file in windows forms application.In present windows stand alone applications you can see different links that redirects us to different websites and shows some images and video contents.Best example for this is Visual studio start page.

Featured Videos
News Feed

If you observe this images you can easy find that those are html links.When we opens visual studio it fetches the html file from server.In current tutorial we will see how to implement this by using WebBrowser control in windows forms application.

Read and Display HTML file in Windows form

1.Create window form application in visual studio.
2.Prepare a html file with image and some text to input for windows form application.
sample.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title></title>
</head>
<body>
    <p>A famous quote of steev is</p>
    <hr />
    <img src='https://pi.tedcdn.com/r/pe.tedcdn.com/images/ted/0ef62e4df27b4ba7294de889fdbc33e476a08ec9_254x191.jpg' />
</body>
</html>

3.Namespaces need to import for this application is as follows
Imports System.IO
Imports System.Reflection

4.Write below code in Form_Load method.
private void Form1_Load(object sender, EventArgs e)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("WebBrowser_HTML_File_CS.sample.htm"));
            webbrowser.DocumentText = reader.ReadToEnd(); 
        }


5.If you observer the above code the html file is loaded into StreamReader object  using  GetManifestResourceStream method.The contents of stram reader are read using ReadToEnd method and assigned to WebBrowser control to display html file in windows forms application.
6.Final output of the application is look like below.


7.Download the source code for this application from here Download.


Wednesday, 25 October 2017

TempData in ASP.NET MVC in C#

22:55:00 Posted by raviteja swayampu No comments
In this article raviteja swayampu explained about how to use TempData in ASP.NET MVC with small example.TempData is a dictionary object to store data temporarily. It is a TempDataDictionary class type and instance property of the Controller base class.

TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary. It  stays for a subsequent HTTP Request(means it can keep live data between two consecutive HTTP requests both request and redirect) as opposed to other options (ViewBag and ViewData) those stay only for current request. So, TempData can be used to maintain data between controller actions as well as redirects.
It will also help to pass state between action methods also and it uses session variable to store data.It is generally used to store one time messages like error messages and validation messages.

Note:  Just like ViewData, typecasting and null checks required for TempData also in order to avoid errors run time errors while rendering cshtml pages and in other action methods.

Lets see how to use tempdata in a practical scenario from one controller to another.
public ActionResult FirstRequest()
{
    List TempDataTest = new List();
    TempDataTest.Add("Raviteja");
    TempDataTest.Add("Krishna");
    TempDataTest.Add("Sridhar");
    TempData["CustomerName"] = TempDataTest;
    return View();
}

public ActionResult ConsecutiveRequest()
{
    List modelData = TempData["CustomerName"] as List;
    TempData.Keep();
    return View(modelData);
}

In View we will display TempData as below.
@{
  if(TempData["CustomerName"]!=null){
 List<string> list=TempData["CustomerName"] as List<string>
 foreach(var item in list){
  //Writing temp data list in html page
  <h3>@item</h3>
 }
  }
}

Generally we do not think about where tempdata is stored.Obviously, it does not matter for developer to think about where it is stored.I hope this information is good about tempdata to know more like base classes of Dictionary class and methods visit MSDN.


Introduction to RequireJS for Modular Programming

05:44:00 Posted by raviteja swayampu No comments
In this tutorial we are going to look at Requirejs an incredibly powerful AMD(Asynchronous Module Definition) compatible script loader.To achieve this modular programming came into picture.

Modular Programming

Modular programming is used to break large applications into smaller blocks of manageable code. Module based coding eases the effort for maintenance and increases reusability of code. However, managing dependencies between modules is a major concern developers face throughout the application development process. Requirejs is one of the most popular frameworks around for managing dependencies between modules.In this tutorial we will see how requirejs helps us.

Why we need Javascript loaders 

Due to evolution of Single page applications web applications requires large number of script files.Generally they all are loaded one by one using <script> tag.Each file can potentially dependent on other script file.A common example for this is jquery plugins in web applications.For all jquery plugins jquery core library file must be loaded.Let look this using a simple real time example.Let's assume we have 3 javascript files.

purchase.js

function purchaseProduct(){
  //gets credits to purchase product
  var credits = getCredits();
  if(credits > 0){
    //checks the product available or not
    reserveProduct();
    return true;
  }
  return false;
}

product.js

function reserveProduct(){
  alert("Function : reserveProduct()");
  return true;
}

credits.js

function getCredits(){
  alert("Function : getCredits");
  var credits = "100";
  return credits;
}
In above example we are trying to purchase a product.First it checks whether credits available or not.If credits are available it reserves the product.Here purchase.js file depends upon credits.js and product.js files.Now in another script file main.js i am initializing code purchase.js as shown below.
var result=purchaseProduct();
So,credits.js and product.js files need to loaded before purchase.js file.We have to place those script files in order.What would happen if we place files in wrong order as shown below.
<script src="products.js"></script>
<script src="purchase.js"></script>
<script src="main.js"></script>
<script src="credits.js"></script>
Here the initialization of script(main.js) is done before credits.js loaded this will result an error like below.



In current example we just have 3 script files for larger applications the number of script files are also more and things can easily get out of control.That's where requirejs come into picture.

Introduction to Requirejs

1.Requirejs is a popular java script module loader which is supported by all latest version browsers.
2.In requirejs we separate code in modules which can handle single responsibility.
3.And dependencies need to be configured before loading script files.
4.Lets start the implementation of an small application by downloading requirejs.
Lets assume our project directory will look like below.


The file main.js file is used for initializing scripts.Lets see how scripts are included in html page using requirejs.

<script data-main="scripts/main" src="~/Scripts/require.js"></script>

This is the only code required to include files using Requirejs.You might be wondering what happened to the other files and how they are included. The data-main attribute defines the initialization point of the application. In this case, it is main.js. Requirejs uses main.js to look for other scripts and dependencies. In this scenario all the files are located in same folder(Scripts folder). you can move the files to any folder you prefer.

Creating Application with Requirejs

 In Requirejs all script code wrapped into require() and define() functions.Lets look at main.js file.

require(["purchase"], function (purchase) {
    purchase.purchaseProduct();
});

1.In above code the first parameter of the function require() specifies dependencies.We already know the initialization dependent on purchase.js file.
Note: Here see the .js extension is omitted. Requirejs only considers .js file only.
2.Second parameter is an anonymous function which takes an object as parameter which is used to call functions inside dependent script files see in above code.
Note: We can load multiple script dependencies using below syntax.

require(["a","b","c"],function(a,b,c){
});

Now we are going to convert the plain script files into Requirejs like below.

purchase.js

 define(["credits","products"], function(credits,products) {
  console.log("Function : purchaseProduct");
  return {
    purchaseProduct: function() {
      var credit = credits.getCredits();
      if(credit > 0){
        products.reserveProduct();
        return true;
      }
      return false;
    }
  }
});

Here,first we declare that purchase functionality depends on credits and products. Inside the return statement, we can define the functions of each module. Here, we have called the getCredits() and reserveProduct() functions on the objects passed. product.js and credits.js are similar, and are shown below.

products.js

define(function(products) {
  return {
    reserveProduct: function() {
      console.log("Function : reserveProduct");
      return true;
    }
  }
});

credits.js

define(function() {
  console.log("Function : getCredits");
  return {
    getCredits: function() {
      var credits = "100";
      return credits;
    }
  }
});

Both files products.js and credits.js are configured as independent modules(defined with define() function).They are dependent on anything.Here the important thing to notice is the difference between require() and define() functions.

Difference between require() and define()

In Requirejs we can use both require() and define() functions to load dependencies.Understanding the difference between this both is essential in managing dependencies.Lets see the differences,

require() 

require function is used to used to run the immediate functionalities.For example we used require in main.js in above example.

define()

define function is used to define modules that are used for multiple locations.In above example we defined products.js and credits.js with define function.The files which are defined by define() function are reusable modules.

Note: In plain java script example, an error was generated due to the incorrect order of file loading. Now, delete the credits.js file in the Requirejs example and see how it works. The following image shows error in browser inspection tool.


The difference here is that no code has been executed in the Requirejs example.We can confirm it since nothing is printed on the console(we wrote console.log in almost every file). In the plain JavaScript example we had some output printed on the console before generating the error. Requirejs waits until all the dependent modules are loaded before executing the functionality. If any modules are missing, it doesn’t execute any code. This helps us maintain the consistency of our data.

Managing order of dependent files

Requirejs uses Asynchronous module loader for loading files.Each dependent module will start loading through asynchronous requests.Even though files ordered is considered due to synchronous nature we can not guarantee that the first file loaded before second file.For that Requirejs allows us to define the sequence of the files using shim config to load in correct order.
Lets how to use shim config,

requirejs.config({
  shim: {
    'source1': ['dependency1','dependency2'],
    'source2': ['source1']
  }
});

Requirejs allows us to provide configuration options using the config() function. It accepts a parameter called shim which we can use to define the mandatory sequences of dependencies see above code.You can find advanced configuration guide in API Documentation of Requirejs.
Using shim config it is mandatory to load dependent before calling files.

Conclusion

I hope this article may helped you to understand the basics of Requirejs.This tutorial is not enough to manage dependencies.You can find advanced tutorial on requirejs from official site documentation.

Saturday, 21 October 2017

How to open a specific jQuery tab on page load?

09:45:00 Posted by raviteja swayampu , No comments
In this article we will see how to load specific tab in jquery ui tabs when page loads.I will explain it with simple example.Lets assume we have three tabs in jquery ui tabs control as shown below.


In the above example we have 3 tabs.Here my requirement is to load 3 tab when page load.Below is jquery script code to achieve this functionality.
$(document).ready(function() {
        //initializing jquery tabs
	$("#tabs").tabs();
	var tabindex=2;
        //selecting tab based on tabindex.
	$("#tabs").tabs('option','active',tabindex);
  });
Source Code:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Tabs - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="http://resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $(document).ready(function() {
	$("#tabs").tabs();
	var tabindex=2;
	$("#tabs").tabs('option','active',tabindex);
  });
  </script>
</head>
<body>
 
<div id="tabs">
  <ul>
    <li><a href="#tabs-1">Nunc tincidunt</a></li>
    <li><a href="#tabs-2">Proin dolor</a></li>
    <li><a href="#tabs-3">Aenean lacinia</a></li>
  </ul>
  <div id="tabs-1">
    <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
  </div>
  <div id="tabs-2">
    <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
  </div>
  <div id="tabs-3">
    <p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
    <p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
  </div>
</div>
</body>
</html>

I hope this article may help you..

Thursday, 5 October 2017

How to make jqgrid responsive for all browsers

11:22:00 Posted by raviteja swayampu , No comments
In this tutorial we gonna learn how grid will be resized on resizing the window of the web browser.Setting of CSS width to 100% is the only one implementation, but it's not good in case of jqGrid which set width in px explicitly on many its internal structures.

jqGrid uses fixed width value on many internal structures (divs, tables and so on). So one can't just set CSS width : 100%. Nevertheless there are another way to do the same. One can register resize event handler on window object and to call setGridWidth explicitly. The method adjust all internals structures of jqGrid to new width. So it would be clean method.


If you use autowidth: true then jqGrid set the width of jqGrid to the width of it's parent only once.So,we have to changes the width of grid every time we resizes the browser window. Inside of $(window).resize handler we can get new (the current) width of the parent and reset the value of grid width. The corresponding code will be the following

$(window).on("resize", function () {
    var $grid = $("#tableelement"),
        newWidth = $grid.closest(".ui-jqgrid").parent().width();
    $grid.jqGrid("setGridWidth", newWidth, true);
});

The event handler changes the width of the grid based on the browser window resizes.Here,I used $("#tableelement").closest(".ui-jqgrid") instead of $("#tableelement") because jqGrid build some dives over the main <table> element. $("#tableelement").closest(".ui-jqgrid") gives as the outer div which include all the elements of the grid see below picture.

How to make jqgrid responsive for all browsers



The script code for responsive jqgrid is as follows.

$(function () {
    debugger;
    $("#grid").jqGrid({
        url: "/Jqgrid/GetValues",
        datatype: 'json',
        mtype: 'Get',
        //table header name 
        colNames: ['Id', 'Name', 'Phone', 'Address', 'DOB'],
       //colModel takes the data from controller and binds to grid 
        colModel: [
            { key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
            { key: false, name: 'Name', index: 'Name', editable: true },
            { key: false, name: 'Phone', index: 'Phone', editable: true },
            { key: false, name: 'Address', index: 'Address', editable: true },
            { key: false, name: 'DOB', index: 'DOB', editable: true, formatter: 'date', formatoptions: { newformat: 'd/m/Y' } }],
            
        pager: jQuery('#pager'),
        rowNum: 10,
        rowList: [10, 20, 30, 40],
        height: '100%',
        viewrecords: true,
        caption: 'Jq grid sample Application',
        emptyrecords: 'No records to display',
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            Id: "0"
        },
        autowidth: true,
        multiselect: false
        //pager-you have to choose here what icons should appear at the bottom
        //like edit,create,delete icons
    }).navGrid('#pager', { edit: true, add: true, del: true, search: false, refresh: true }
    });
});
//event handler to resize the width of grid
$(window).on("resize", function () {
    var $grid = $("#grid"),
        newWidth = $grid.closest(".ui-jqgrid").parent().width();
    $grid.jqGrid("setGridWidth", newWidth, true);
});


See the responsive grid for demo at jsfiddle responsive jqgrid.
Related articles on jqgrid as follows,

I hope this article may help you.For more related article follow mitechdev.com.