Thursday, December 13, 2012

Reading and Writing Text Files c sharp


Writing to a Text File

TextFileWriter.cs

using System;using System.IO;namespace csharp_station.howto
{
   class TextFileWriter
   {
       static void Main(string[] args)
       {
            // create a writer and open the file            TextWriter tw = new StreamWriter("date.txt");
           // write a line of text to the file
            tw.WriteLine(DateTime.Now);
           // close the stream
            tw.Close();
       }
   }
}

Reading From a Text File

TextFileReader.cs

using System;using System.IO;namespace csharp_station.howto
{
   class TextFileReader
   {
       static void Main(string[] args)
       {
            // create reader & open file            Textreader tr = new StreamReader("date.txt");
           // read a line of text
            Console.WriteLine(tr.ReadLine());

            
// close the stream            tr.Close();
       }
   }
}

Fetching Web Pages


WebFetch.cs
using System;
using System.IO;
using System.Net;
using System.Text;


/// <summary>
/// Fetches a Web Page
/// </summary>
class WebFetch
{
 static void Main(string[] args)
 {
  // used to build entire input
  StringBuilder sb  = new StringBuilder();

  // used on each read operation
  byte[]        buf = new byte[8192];

  // prepare the web page we will be asking for
  HttpWebRequest  request  = (HttpWebRequest)
   WebRequest.Create("http://solve-dotnet.blogspot.in/");

  // execute the request
  HttpWebResponse response = (HttpWebResponse)
   request.GetResponse();

  // we will read data via the response stream
  Stream resStream = response.GetResponseStream();

  string tempString = null;
  int    count      = 0;

  do
  {
   // fill the buffer with data
   count = resStream.Read(buf, 0, buf.Length);

   // make sure we read some data
   if (count != 0)
   {
    // translate from bytes to ASCII text
    tempString = Encoding.ASCII.GetString(buf, 0, count);

    // continue building the string
    sb.Append(tempString);
   }
  }
  while (count > 0); // any more data to read?

  // print out page source
  Console.WriteLine(sb.ToString());
 }
}

Wednesday, September 26, 2012

Difference between IList and List in c#


If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the users of your library won't need to update their code since the interface doesn't change.
If you are just using it internally, you may not care so much, and using List may be ok.

Tuesday, September 25, 2012

[required] Conditional Validation with Data Annotations in ASP.NET MVC4

When the user want some fields are Required some time’s . But some times  user don’t  Required some fields for example
In registration time  we want username and password field but  change password time only we want password field .In this situation we would create two models .To avoid this problem using removing the fields from the model state, it won’t be invalid when they are missing.  This method is simple and avoids adding additional dependencies.
    public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
         }
    public ActionResult ChangePassword()
    {
        ModelState.Remove("Password");
        return View();
    }


  abiruban



Monday, September 3, 2012

Razor View Engine


According to my knowledge Asp.net has been two  view engine ‘s 
1) .aspx view engine
2) Razor view engine
. aspx view engine, which everyone knew about so let we describe the blog  Razor view engine
Razor was designed as an easy to learn, compact and expressive view engine that enables a fluid coding workflow. Razor file extension is ‘cshtml’ for C# language, and ‘vbhtml’ for Visual Basic. In existing .aspx view engine using the <%= %>  but
Razor view engine strats with @ it is very simpler,neat and light weight than aspx view engine
For example
Razor view engine
Todays date   @DateTime.Now

.aspx view engine
Todays date  <%= DateTime.Now %>
More about razor view engine refer scottgu  blog  
Thanks
Abiruban



Wednesday, August 22, 2012

What is MVVM



Model-View-ViewModel (MVVM). The MVVM pattern allows applications to be divided up into separate layers that provide multiple benefits ranging from better code re-use to enhanced    testing   capabilities.




Tuesday, July 10, 2012

Jquery Showing an element


Showing an element by id

The following example demonstrates how you make a hidden <div> element
with an id appear when someone clicks a button on your page:

1.    Create a Web page containing the following code:

<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <title>My Test Page</title>
    <script type="text/javascript" src="js/jquery-1.4.min.js"></script>
    <script type="text/javascript">
        $(':submit').click(function () {
            $('#showme').show();
        });
    </script>
</head>
<body>
    <div id="showme" style="display: none">
        This will appear.</div>
    <input value="Show" type="submit"></body>
</html>

This code contains a <div> element with an id attribute named
showme. This <div> element is set as hidden using the CSS style attribute
set to display:none.

        $(':submit').click(function () {
            $('#showme').show();
        });


The code says, “When the button is clicked, show the element with the
showme id.” This code uses the :submit selector and the click event
to set up the action. The show function, with an id selector, displays the
element with the showme id.

2.     Save the file, and then view it in your browser.

Showing an element with animation

When you show a hidden element, it disappears instantly. As with the hide
function, the show function allows you to make it appear as though the element
is fading in. To add fade in animations when elements are displayed,
follow these steps:
1. Create a Web page containing the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <title>My Test Page</title>
    <script type="text/javascript" src="js/jquery-1.4.min.js"></script>
    <script type="text/javascript">
        $(':submit').click(function () {
            $('#slowshow').show(2000);
            $('#fastshow').show(500);
        });
    </script>
</head>
<body>
    <div id="slowshow" style="display: none">
        This will be shown slowly.</div>
    <div id="fastshow" style="display: none">
        This will be shown quickly.</div>
    <input value="Show" type="submit">
</body>
</html>


This code contains two <div> elements and a button.

        $(':submit').click(function () {
            $('#slowshow').show(2000);
            $('#fastshow').show(500);
        });

The code says, “When the button is clicked, show the element with the
slowshow id at a speed of 2000 milliseconds. Show the element with
the fastshow id at a speed of 500 milliseconds.” This code uses the
:submit selector and the click event to set up the action.
2. Save the file, and then view it in your browser.


Refer from Jquery books and google
Thanks..

Jquery Hiding an element


Hiding an element by type with a button
The following example shows you how you make everything inside <div>
elements disappear when a user clicks a button on your page:

1. Create a Web page containing the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <title>My Test Page</title>
    <script type="text/javascript" src="js/jquery-1.4.min.js"></script>
    <script type="text/javascript">
        $(':submit').click(function () {
            $('div').hide();
        });
    </script>
</head>
<body>
    <div>
        This will be hidden.</div>
    <div>
        This will be hidden.</div>
    <input value="Hide" type="submit">
</body>
</html>

This code contains two <div> elements and a button.
2. Save the file, and then view it in your browser.

3. Click the button.
Everything in both <div> elements is now hidden

Hiding an element by id when clicked
The next example shows you how you make everything inside a <div> element
with an id disappear when someone clicks that <div> element:

1.     Create a Web page containing the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <title>My Test Page</title>
    <script type="text/javascript" src="js/jquery-1.4.min.js"></script>
    <script type="text/javascript">
        $('#hideme').click(function () {
            $('#hideme').hide();
        });
    </script>
</head>
<body>
    <div id="hideme">
        This will be hidden.</div>
    <div>
        This will not be hidden.</div>
</body>
</html>

This code contains a <div> element with an id attribute named
hideme. Unlike the preceding example, there is no button.

2. Save the file, and then view it in your browser.



Refer from Jquery books and google
Thanks..

Calling Your JavaScript Code after the Page Loaded


Calling Your JavaScript Code after the Page Has Loaded

Sometimes you will want to execute JavaScript code only when the user tries
to leave your page. You might want to do this because you want to bid the
user farewell or remind the user he or she is leaving your site.
Doing this requires two steps:
• Place the code you want to execute after the page has completed
loading into a function.
• Use the onUnload attribute of the body tag to call the function.
This results in code like the following:
<script language="JavaScript">
function functionName() {
Code to execute when the page finishes loading
}
</script>
</head>
<body onUnload="functionName();">
Body of the page
</body>

</head>
<body>
The following task creates a function that displays a goodbye message in a dialog
box and then only invokes that function when the user leaves the page:
1. Open a new HTML document in your preferred HTML or text editor.
2. Create the header of the document with opening and closing head tags.
3. Insert a script block in the header of the document.
4. Create a function named bye that takes no arguments:
function bye() {
}

5. In the function, use the window.alert method to display an alert
dialog box:
window.alert(“Farewell”);
6. Create the body of the document with opening and closing body tags.
7. In the body tag, use the onUnload attribute to call the bye function:
<body onUnload=”bye();”>
8. In the body of the page, place any HTML or text that you want in
the page so that the final page looks like Listing below code
<head>
<head>
<script language="JavaScript">
<!--
function bye() {
window.alert(“Farewell”);
}
// -->
</script>
</head>
<body onUnload="bye();">
The page’s content.
</body>

Using onUnload to call a function after the user leaves a page.
9. Save the file.
10. Open the file in a browser, and you should see the page’s content.
Navigate to another site and you should see the farewell dialog box.

Friday, July 6, 2012

Exception Handling


An exception is an error that occurs at runtime. Using C#’s exception handling subsystem, you can, in a structured and controlled manner, handle runtime errors. C#’s approach to exception handling is a blend of and improvement on the exception handling mechanisms used by C++ and Java. Thus, it will be familiar territory to readers with a background in either of these languages. What makes C#’s exception handling unique, however, is its clean, straightforward implementation.

A principal advantage of exception handling is that it automates much of the error-handling code that previously had to be entered “by hand” into any large program. For example, in a computer language without exception handling, error codes must be returned when a method fails, and these values must be checked manually, each time the method is called. This approach is both tedious and error-prone. Exception handling streamlines error-handling by allowing your program to define a block of code, called an exception handler, that is executed automatically when an error occurs. It is not necessary to manually check the success or failure of each specific operation or method call. If an error occurs, it will be processed by the exception handler.

Another reason that exception handling is important is that C# defines standard exceptions for common program errors, such as divide-by-zero or index-out-of-range. To respond to these errors, your program must watch for and handle these exceptions.
In the final analysis, to be a successful C# programmer means that you are fully capable of navigating C#’s exception handling subsystem.

Refer from C# books....

Friday, June 15, 2012

Watin Tool


In this blog iam describe the implementation and usage of watin
Watin is the one of the most  powerful  visual studio testing tool .watin tool develop in C# and the main goal  automating   the browser and test the project. watin can get and set values from the elements in a form, and you can fire events of any of the elements 

Download the watin click here
Following is the Hello world example of web test automation: searching Google.

[Test]
public void SearchForWatiNOnGoogle()
{
  using (var browser = new IE("http://www.google.com"))
  {
    browser.TextField(Find.ByName("q")).TypeText("WatiN");
    browser.Button(Find.ByName("btnG")).Click();
  
    Assert.IsTrue(browser.ContainsText("WatiN"));
  }
}

HTMLAgilityPack


In this blog iam describe the implementation and usage of HTMLAgilityPack
HtmlAgilityPack is one of the great open sources projects I ever worked with. It is a HTML parser for .NET applications, works with great performance, supports malformed HTML.
HTMLAgilityPack is used to retrieve the value from browser. The main goal of the HTMLAgilityPack
Website crawling or screen scraping

Download and build the HTMLAgilityPack solution.

The sample code are here


Take the html hidden value

var webGet = new HtmlWeb();
            var document = webGet.Load(url);
            var value = document.DocumentNode.SelectSingleNode("//input[@type='hidden' and @name='mob']")
                .Attributes["value"].Value;


Take the html td value



var webGet = new HtmlWeb();
            var document = webGet.Load(url);

            foreach (HtmlNode li in document.DocumentNode.SelectNodes("//td[@class='textnopad']"))
            {
                if(li.InnerText.Contains("91"))
                {
                    string mob = li.InnerText;
                }
            }
 Take the html anchor  tag value

var webGet = new HtmlWeb();
            var document = webGet.Load(url);
            var linksOnPage = from lnks in document.DocumentNode.Descendants()
                              where lnks.Name == "a" &&
                                    lnks.Attributes["href"] != null &&
                                     lnks.Attributes["href"].Value.Contains(id)
                                   
                              select new
                              {
                                  Url = lnks.Attributes["href"].Value,
                                  Text = lnks.InnerText

                              }.Url;

  Take the html anchor  tag value

var webGet = new HtmlWeb();
            var document = webGet.Load(url);
              foreach (HtmlNode li in document.DocumentNode.SelectNodes("//div[@id='cssBox']"))
            {
                string mob = li.InnerText;
            }