Wednesday 30 January 2013

Unit Testing For Entity Framework 4.0


This article gives you an ultra-fast run down on how to start Unit Testing in Entity Framework 4.0 using C#; applying a suitable Code Generation Item to your Entity Data Model (EDMX) file, and building a Unit Test Project in Visual Studio 2010.

No external test harness is required, it doesn't rely on having a Repository pattern being implemented and you don't need to buy any new products. Just Visual Studio 2010 Professional Edition, Premium Edition or Ultimate Edition out of the box.




Terminology
The EDMX Code Generation Item used in this article generates two ObjectContext classes. When we refer to the Vanilla ObjectContext, this is the same strongly typed ObjectContext that is generated from your EDMX by default. The Mocking ObjectContext we refer to is another context used only for unit testing, which implements the same strongly typed interface, and is also generated from your EDMX file.

More details on the architecture of the artifact generator are provided here.


Step 1: Set Up the Code Generation Item

These steps will change your EDMX Code Generation Item to the ADO.NET Mocking Context Generator. This is what makes your C# code from your Entity Data Model (EDMX) file.

Open your EDMX file, right click the background, and from the context menu select Add Code Generation Item.

Select Online Templates->Database->ADO.NET Mocking Context Generator:


  • Open your EDMX file, right click the background, and from the context menu select Properties.
  • In the Properties change Code Generation Strategy to None. This will turn off the default Code Generation Item.



Step 2: Ensure "Context Agnostic" Code

Context Agnostic means that your Business Logic code shouldn't be aware of what context class it is using. We need to ensure that any hard dependencies on your generated Vanilla ObjectContext are replaced with references to your new generated ObjectContext Interface instead.

Identify Context "Gnostic" Code

We need to find anywhere in your Business Logic Layer that references the vanilla concrete ObjectContext:

class MovieLogic
{
    private MoviesContext _context;     // Hard dependency on vanilla ObjectContext

    public MovieLogic()
    {
        _context = new MoviesContext();     // Hard dependency on vanilla ObjectContext
    }
}

Option 1: Delegate responsibility to the client

To remove the hard dependency, the simplest option is to ensure all ObjectContext references use the ObjectContext Interface instead, and take on the ObjectContext instance in their constructor:
class MovieLogic
{
    private IMoviesContext _context;    // Interface used instead: context agnostic

    public MovieLogic( IMoviesContext context )
    {
        _context = context;     // Instantiation responsibility is delegated to caller
    }
}
The Business Logic Client can then be re-engineered to instantiate a vanilla ObjectContext object for us when the Business Logic object is instantiated:
MovieLogic logic = new MovieLogic( new MoviesContext() );
Note
Your application will never instantiate a Mocking Context, as this is only used when testing your business logic in your Unit Test Project.



Option 2: Delegate responsibility to a factory

If your Business Logic objects are instantiated all over the place, then it might be easier to contain the instantiation responsibility within a factory, and call the factory when a context is needed from the Business Logic objects themselves:

class MovieLogic
{
    private IMoviesContext _context;

    public MovieLogic()
    {
        _context = MyContextFactory.CreateContext();    
            // Instantiation responsibility is delegated to factory
    }
}
Implementing the Factory
Whilst no implementation of an example factory is given here, the factory just needs to return a new instance of your Vanilla ObjectContext, unless the "testing" flag is raised, when a Mocking ObjectContext will be instantiated instead.



Step 3: Create the Unit Tests

To create the unit tests in Visual Studio, a new test project needs to be created. This project will contain the Unit Test class that runs all the tests, and the code required to set up the mocking context, mock data, and the calls to the business logic.

Right click your solution, and select Add -> New Project

From the Add New Project Dialog select Visual C# -> Test -> Test Project:



  • Add a Reference in your new test project to your Business Logic Project.
  • Add a Reference to System.Data
  • Add a Reference to System.Data.Entity

  • Set up the test "database"
  • This step creates a fresh mocking context before every test is executed. The mocking context is populated with some sample data that the tests can use. Additionally any test can set up its own data as part of its testing.
  • In your new test project, open your Unit Test code file (eg. "UnitTest1.cs")
  • Add a member (eg. _context) to your unit test class, of the type of your ObjectContext Interface. The name of the interface will be shown if you expand the *.Context.tt file in the project containing your EDMX file:

  • private IMoviesContext _context;
  • Add a new function with the TestInitialize attribute. This will cause your function to be executed before every test. Create a mock context and fill it with your mock data. The name of the mocking context class will be shown if you expand the *.Context.tt file in the project containing your EDMX file:

    [TestInitialize]
    public void TestInitialize() 
    { 
        _context = new MoviesContextMock();
    
        Actor[] actors = new Actor[]
        {
            new Actor() { Id = 1, Name = "Robert De Niro" },
            new Actor() { Id = 2, Name = "Ray Liotta" },
            new Actor() { Id = 3, Name = "Joe Pesci" },
            new Actor() { Id = 4, Name = "Jodie Foster" }
        };
    
        Movie[] movies = new Movie[]
        {
            new Movie() { Id = 1, Title = "Goodfellas",  ReleaseYear = 1990, Rating=5 },
            new Movie() { Id = 2, Title = "Taxi Driver", ReleaseYear = 1976, Rating=5 },
        };
    
        movies[ 0 ].Cast.Add( actors[ 0 ] );
        movies[ 0 ].Cast.Add( actors[ 1 ] );
        movies[ 0 ].Cast.Add( actors[ 2 ] );
        movies[ 1 ].Cast.Add( actors[ 0 ] );
        movies[ 1 ].Cast.Add( actors[ 3 ] );
    
        actors.ToList().ForEach( actor => _context.Actors.AddObject( actor ) );
        movies.ToList().ForEach( movie => _context.Movies.AddObject( movie ) );
    }


Implement Test Methods

Create some functions on your new unit test class, with the attribute TestMethod. These will execute the individual unit tests for your business logic.


Use the Assert.* methods to check the results of calls to your business logic. These calls will be evaluated by the test engine.


[TestMethod]
public void TestGetMovieByTitle()
{
    MovieLogic logic = new MovieLogic( _context );
    Movie movie = logic.GetMovieByTitle( "Goodfellas" );
    Assert.AreEqual( 1, movie.Id );
}

[TestMethod]
public void TestGetMovieByTitleBad()
{
    MovieLogic logic = new MovieLogic( _context );
    Movie movie = logic.GetMovieByTitle( "Arial the Little Mermaid" );
    Assert.AreEqual( null, movie );
}

[TestMethod]
public void TestGetMovieByReleaseYear()
{
    MovieLogic logic = new MovieLogic( _context );
    Movie[] movies = logic.GetMovieByReleaseYear( 1976 );
    Assert.AreEqual( 1, movies.Length );
    Assert.AreEqual( "Taxi Driver", movies[ 0 ].Title );
}



Running the Tests

To run the tests, select Test -> Run -> All Tests In Solution.

The Test Results panel will pop up, and give you the results of your tests:




Frequently Asked Questions

Where's my Vanilla ObjectContext's AddToObjectSetName method gone?

This method has now been deprecated in Entity Framework 4.0. Instead of using AddToObjectSetName, use <My Vanilla ObjectContext>.<ObjectSetName>.AddObject(). 


How do I unit test my EDMX EntityObject Functions?

Functions map to Stored Procedures in your database. You cannot, therefore, unit test your C# code and expect to call an SP as part of the unit test. You'll have to make sure that the high level logic function that calls the stored procedure is not included in your code C# tests; if you can break the function down into smaller method units within the logic class you may still be able to test the smaller logic units that don't require the SP. For unit testing the SP however, you need to create a Database Unit Test project. 


How do I perform a unit test that includes database connectivity?

This, semantically speaking, is not possible. A code Unit Test should be testing units of code. If you need to perform a test across your code into a persistent storage medium, then this is an Integration Test. The Unit Testing phase is performed before the Integration Testing phase.


Happy coding ......

Friday 25 January 2013

enum in c#


Enums store special values. They make programs simpler. If you place constants directly where used, your C# program becomes complex. It becomes hard to change. Enums instead keep these magic constants in a distinct type.

Example

In this first example, we see an enum type that indicates the importance of something. An enum type internally contains an enumerator list. You will use enum when you want readable code that uses constants.
An enum type is a distinct value type that declares a set of named constants.
Program that uses enums [C#]

using System;

class Program
{
    public enum PageName
    {
        Any = 0,
        Index = 1,
        About = 2
    }

    static void Main()
    {
     Console.WriteLine(PageName.Any);
 
    }
}

Output

0

Monday 21 January 2013

DataTable To String Array in C#

Many time we need need to get data from dataset\Datatable to array to pass it to some function or third API like x axis or y axis series of chart controls or to some other reporting or data binding control may be dropdown. it becomes difficult to get the data of a column(s) in array and finally we end up writing a for loop. here is a sample example by which we can simply get array of a column(s) with out a for loop
public static string DataRowToString(DataRow dr)
{
       return dr["columns"].ToString();
}
public string [] DataTableToArray(DataTable dt)
{
     DataRow[] dr = dt.Select();
     string [] strArr= Array.ConvertAll(dr, newConverter(DataRowToString));
     return strArr;
}


Array.ConvertAll() function simply converts the array of one to another so here in above example we are passing dr as an araay of datarows in first arguments. second argument is aConverter delegate type which convert one type to another so in this we will pass a link to delegate which is DataRowToString() function ,the delegate should know the input datatype and output datatype which is datatrow and string in this case respectively. function DataRowToString noe simply takes a datarow and return the string value for the column specified. which can be extended for multiple columns also.

Saturday 19 January 2013

Radio button selected in asp.net


Please try this way(sample code)


Html

<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <title>Show RadioButton</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    How did you hear about our Website?
    
    <ul>
        <li>
        <asp:RadioButton
            id="rdlMagazine"
            Text="Magazine Article"
            GroupName="Source"
            Runat="server" />
        </li>
        <li>
        <asp:RadioButton
            id="rdlTelevision"
            Text="Television Program"
            GroupName="Source"
            Runat="server" />
        </li>
        <li>
        <asp:RadioButton
            id="rdlOther"
            Text="Other Source"
            GroupName="Source"
            Runat="server" />
        </li>
    </ul>
    
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" OnClick="btnSubmit_Click" />
   
    <hr />
    
    <asp:Label
        id="lblResult"
        Runat="server" />
    
    </div>
    </form>
</body>
</html>

C#



protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (rdlMagazine.Checked)
            lblResult.Text = rdlMagazine.Text;
        if (rdlTelevision.Checked)
            lblResult.Text = rdlTelevision.Text;
        if (rdlOther.Checked)
            lblResult.Text = rdlOther.Text;
    }

Difference Between Static And Non Static Method

I will use a slightly different example.  Consider

public class Dog {
   public string Name; // An instance field
   private int weight; // A private instance field
   public static int Population; // A static field
   private static int totalWeight;  // A private static field


   public Dog(string name) {
      Name = name;   // Set the name of this particular Dog
      weight = 500;  // Dogs weight 500g when they are born


      Population++;  // We have one more Animal
      totalWeight += 500;  // The total weight of all Dogs increases by 500g
   }


   public void FeedMe(int foodWeight) {  // An instance method
                                         // because you feed a particular animal
      weight += foodWeight;  // When you feed a particular Dog it gets heavier
      totalWeight += foodWeight;  // The total weight of all Dogs increases
   }


   public static int AverageWeight() {
      return totalWeight / Population;
   }


   public int CurrentWeight() {  // An instance method
      return weight;
   }
}
 You can create and feed a Dog with

Dog MyPet = new Dog("Rover");
MyPet.Feed(200);
Console.WriteLine(MyPet.CurrentWeight); // Prints 700
MyPet.Feed(400);
Console.WriteLine(MyPet.CurrentWeight); // Prints 1100
 and also

Dog yourPet = new Dog("Fido");
yourPet.Feed(400);
Console.WriteLine(yourPet.CurrentWeight); // 900
 What is the average weight of all Dogs?

Console.WriteLine(Dog.AverageWeight); // Prints 1000

No particular Dog knows the average weight of all Dogs.  The method AverageWeight() only uses static fields of the class Dog.  You could declare AverageWeight without static but then you would have to say

Console.WriteLine(MyPet.AverageWeight);  // Prints 1000, YourPet.AverageWeight would give the same answer.

But this would be confusing because the method does not compute the average weight of a particular Dog but rather of all Dogs.

You might like to download and read this fantastic, free book written by the man (Charles Petzold) which, in my opinion, is a great introduction to C#.


PS - My Dog population never goes down and no Dog ever loses weight.  It is an exercise for the reader to handle death, exercise and diets.  Also, in a real application you would need to consider thread safety.

PPS - I realise English is not your first language but using real words rather than SMS speak is a lot friendlier for old people, like me.

Convert Dataset to DataTable


Check this sample code


public DataTable ConvertDvToDt(int division)
    {
        DataView dv = _mtc.GetMatchResults(division);
        DataTable dt = new DataTable();
        // dt.Columns.Add("id", Type.GetType("System.String")).AutoIncrement.ToString();
        dt.Columns.Add("MatchId", Type.GetType("System.String"));
        dt.Columns.Add("MatchDate", Type.GetType("System.String"));
        dt.Columns.Add("TeamName", Type.GetType("System.String"));
        dt.Columns.Add("PlayerName", Type.GetType("System.String"));
        dt.Columns.Add("TeamOneScore", Type.GetType("System.String"));
        dt.Columns.Add("UserId", Type.GetType("System.String"));
        dt.Columns.Add("LoginUserId", Type.GetType("System.String"));
        dt.Columns.Add("TeamId", Type.GetType("System.String"));
        DataColumn[] myPrimaryKeyColumn = new DataColumn[1];
        myPrimaryKeyColumn.SetValue(dt.Columns[0], 0);
        dt.PrimaryKey = myPrimaryKeyColumn;
        DataTable dtSetAndScore = dv.ToTable(true, "MatchId", "TeamId", "SetNo", "Score");
        DataTable dtTeam = dv.ToTable(true, "MatchId", "TeamName", "TeamId");
        DataTable dtPlayer = dv.ToTable(true, "MatchId", "Name");
        DataTable dtDate = dv.ToTable(true, "MatchId", "MatchDate", "UserId");

        for (int i = 0; i <= dtTeam.Rows.Count - 1; i++)
        {
            DataRow row = dt.NewRow();
            int Matchid = Convert.ToInt32(dtTeam.Rows[i]["MatchId"]);

            //row = dt.NewRow();
            DataRow[] drSelect = dtTeam.Select("MatchId=" + Matchid);
            string temp = drSelect[0]["TeamName"].ToString();
            string temp1 = drSelect[0]["TeamId"].ToString();

            for (int y = 1; drSelect.Length > y; y++)
            {
                temp = temp + "<br/>" + drSelect[y]["TeamName"].ToString();
                temp1 = temp1 + "<br/>" + drSelect[y]["TeamId"].ToString();
            }
            DataRow dr = dt.Rows.Find(Matchid);
            if (dr == null)
            {
                row["MatchId"] = Matchid;
                row["TeamName"] = temp;
                row["TeamId"] = temp1;
                dt.Rows.Add(row);
            }

        }
        DataView dvPlayerName = new DataView();
        dvPlayerName = dtPlayer.DefaultView;
        DataTable dtName = dvPlayerName.ToTable();
        dtPlayer = dvPlayerName.ToTable(true, "MatchId");
        for (int k = 0; k <= dtPlayer.Rows.Count - 1; k++)
        {
            DataRow row = dt.NewRow();
            int Matchid = Convert.ToInt32(dtPlayer.Rows[k]["MatchId"]);
            DataRow[] drPlayerSelect = dtName.Select("MatchId=" + Matchid);
            string PlayerName = drPlayerSelect[0]["Name"].ToString();
            for (int y = 0; drPlayerSelect.Length > y; y++)
            {
                if (y == 1)
                {
                    PlayerName = PlayerName + " / " + drPlayerSelect[y]["Name"];
                }
                else if (y == 2)
                {
                    PlayerName = PlayerName + "<br/>" + drPlayerSelect[y]["Name"];
                }
                else if (y == 3)
                {
                    PlayerName = PlayerName + " / " + drPlayerSelect[y]["Name"];
                }
            }
            string TotalPlayerName = PlayerName.ToString();

            dt.Rows[k]["MatchId"] = Matchid;
            dt.Rows[k]["PlayerName"] = TotalPlayerName;
            dt.AcceptChanges();

        }
        DataView dvSetAndScore = new DataView();
        dvSetAndScore = dv;
        DataTable dtScore = dvSetAndScore.ToTable("Score");
        string Score = "";
        DataView dvMatch = dtScore.DefaultView;
        DataTable dtMatch = dvMatch.ToTable(true, "MatchId");
        for (int i = 0; i <= dtMatch.Rows.Count - 1; i++)
        {

            DataRow row = dt.NewRow();
            int Matchid = Convert.ToInt32(dtMatch.Rows[i]["MatchId"]);
            DataRow[] drScore = dtSetAndScore.Select("MatchId=" + Matchid);
            for (int j = 0; j <= drScore.Length - 1; j++)
            {
                Score = drScore[j]["Score"].ToString();
                Score = Score + ",";
                if (j == 2 || j == 5)
                {
                    Score = Score.Substring(0, (Score.Length - 1));
                    Score = Score + "<br/>";
                }
                Score = Score.ToString();
                dt.Rows[i]["MatchId"] = Matchid;
                dt.Rows[i]["TeamOneScore"] += Score;

            }
            dt.AcceptChanges();

        }
        for (int i = 0; i <= dtDate.Rows.Count - 1; i++)
        {
            DataRow row = dt.NewRow();
            int Matchid = Convert.ToInt32(dtDate.Rows[i]["MatchId"]);
            Guid userId = (Guid)dtDate.Rows[i]["UserId"];
            DataRow[] drScore = dtDate.Select("MatchId=" + Matchid);
            DateTime AddedDate = Convert.ToDateTime(dtDate.Rows[i]["MatchDate"]);
            dt.Rows[i]["MatchId"] = Matchid;
            dt.Rows[i]["MatchDate"] = String.Format("{0:M/d/yyyy}", AddedDate);
            dt.Rows[i]["UserId"] = userId;
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                MembershipUser userInfo = Membership.GetUser(HttpContext.Current.User.Identity.Name);
                Guid LoginUserId = new Guid(userInfo.ProviderUserKey.ToString());
                if (LoginUserId == userId)
                {
                    //lblEdite.Visible = true;
                }
                else
                {
                    //lblEdite.Visible = false;
                }
                dt.Rows[i]["LoginUserId"] = LoginUserId;
            }
            else
            {
                //lblEdite.Visible = false;
            }
            dt.AcceptChanges();
        }
        return dt;
    }

Thursday 10 January 2013

User role base Div style in MVC

User role base Div Style  

If the user was editor,then i was assigned account type an edit was true

Now use this code


<div class="contactedNameStyle" style='display:@(Model.AccountType == MakeMeChangeMyJob.Models.AccountType.User && Model.Type == MakeMeChangeMyJob.Models.ModelType.Edit ? "block" : "none")'>
                @Html.LabelFor(m => m.AllowAllRecruiters)
                @Html.RadioButtonFor(m => m.AllowAllRecruiters, true, new { @selected = true })
                @MakeMeChangeMyJob.Strings.AllowAllRecruiters
                <br />
                @Html.RadioButtonFor(m => m.AllowAllRecruiters, false) @MakeMeChangeMyJob.Strings.SpecifyPreferences
</div>


for that account type is witch type of user and model type of now what process running (Add,Edit,Update). in our application

Tuesday 8 January 2013

Delete cookies


To assign a past expiration date on a cookie
Determine whether the cookie exists, and if so, create a new cookie with the same name.
Set the cookie's expiration date to a time in the past.
Add the cookie to the Cookies collection object.
The following code example shows how to set a past expiration date on a cookie.

VB

If (Not Request.Cookies("UserSettings") Is Nothing) Then
    Dim myCookie As HttpCookie
    myCookie = New HttpCookie("UserSettings")
    myCookie.Expires = DateTime.Now.AddDays(-1D)
    Response.Cookies.Add(myCookie)
End If


C#

if (Request.Cookies["UserSettings"] != null)
{
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}

Thursday 3 January 2013

Minification and Bundling


Minification and Bundling in MVC3


I have been testing ASP.net MVC4 lately and one of the things I really like in it is the built in minification and bundling that it provides. I discovered the other day that there is a nuget package that contains this MVC4 bundling and minification. The problem I ran into with the nuget package is that it uses a different namespace than the actual file in MVC4. The nuget package uses Microsoft.Web.Optimization and MVC4 uses System.Web.Optimization so I was unable to get the nuget package to work properly in my view. Then I thought to myself “I already have the actual file in my MVC4 project”, so I grabbed it from my project and dropped it into the bin folder of my MVC3 project and added a reference to it. What do you know, it works!!
So here is how to use it:
  1. Reference the System.Web.Optimization dll file in your project. I suggest getting it from an MVC4 project or downloading it here.
  2. Open up your global.asax file and add this line to the end of your Application_Start() function.
1)BundleTable.Bundles.EnableDefaultBundles();
Add bundling to your view(s)
@using System.Web.Optimization <link rel="stylesheet" type="text/css" href="@BundleTable.Bundles.ResolveBundleUrl("~/stylesheets/css")" /> <script type="text/javascript" src="@BundleTable.Bundles.ResolveBundleUrl("~/scripts/js")"></script>


The last part of the bundling path is the file type to bundle, so in my examples the paths are actually “/stylesheets” & “/scripts”. This takes all of the css files in the stylesheets folder and combines and minifies them into a single file. It does the same thing with the js files in the scripts folder.
The output will look similar to this:
<link rel="stylesheet" type="text/css" href="/stylesheets/css?v=oI5uNwN5NWmYrn8EXEybCIbINNBbTM_DnIdXDUL5RwE1" />
<script type="text/javascript" src="/scripts/js?v=cuu54Mg4FexvXMQmXibMetb08jdn7cTR1j-MSVxFRPE1"></script>

As you can see, it gives the bundled files a version id so that you can cache the files and when you make a change to one of them, the ID will change so that your browser will download the new changes.
Just as a warning, MVC4 is still in beta so be careful with using this file. The final version of the system.web.optimization will probably be different


Refer from : http://joeyiodice.com/







Convert sql to Linq

Hai

Please go this url
http://www.sqltolinq.com/downloads , and download that convertor your liked versions

and open that.set connection string and click convert button.

Tuesday 1 January 2013

SQL SERVER – What is – DML, DDL, DCL and TCL – Introduction and Examples


DML

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.

Examples: SELECT, UPDATE, INSERT statements

DDL

DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.

Examples: CREATE, ALTER, DROP statements

DCL

DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.

Examples: GRANT, REVOKE statements

TCL

TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database.

Examples: COMMIT, ROLLBACK statements

Image Slider using jQuery

I have seen a lot of users requesting for simple jQuery scripts for SlideShows.
I saw a couple of them, but the scripts assumed that the number of image tags has to be fixed beforehand.

Update: There is a updated version of this article at Simple Image SlideShow using jQuery

I thought of making an attempt at a real simple SlideShow script using jQuery.
 Here’s what I came up with 5 lines of jQuery code.
 The images have been added to a ‘images’ folder kept at the root.
The images has been defined in an array which can be retrieved from a server.
 For simplicity sake, I have harcoded the images paths, however the script functionality
can adapt dynamically to the number of images in the array.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Simple Slide Show with jQuery</title>
    <script type='text/javascript'
    src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
    </script>
    <script type="text/javascript">
        var imgs = [
        'images/emo.jpg',
        'images/icon068.gif',
        'images/icon260.jpg'];
        var cnt = imgs.length;

        $(function() {
            setInterval(Slider, 3000);
        });

        function Slider() {
        $('#imageSlide').fadeOut("slow", function() {
           $(this).attr('src', imgs[(imgs.length++) % cnt]).fadeIn("slow");
        });
        }
</script>
</head>
<body>
    <img id="imageSlide" alt="" src="" />
</body>
</html>
The code is not perfect but will give you an idea of how to extend
this sample to suit your own requirements. You can see a Live Demo here.


There are many jQuery image gallery plugins:

http://speckyboy.com/2009/06/03/15-amazing-jquery-image-galleryslideshow-plugins-and-tutorials/

Here's an example of using the jQuery Galleria plugin with ASP.NET MVC:

http://aspalliance.com/1864_Aspnet_mvc_image_gallery.all







Forecolor in asp Text Box


TextBox1.ForeColor = Color.Red;
TextBox1.Font.Bold = True;


Or this can be done using a CssClass (recommended):

.highlight
{
  color:red;
  font-weight:bold;
}

codebehind
TextBox1.CssClass = "highlight";
or,Design source
<asp:TextBox id="TextBox1" runat="server" CssClass="highlight"></asp:TextBox>

Or the styles can be added inline:

TextBox1.Attributes["style"] = "color:red; font-weight:bold;";

print one part in form asp.net


No print preview, but this will print only the specified <div> tag:

<form id="Form1" method="post" runat="server">
 <div id="Div1">
  Printable content
 </div>
 <input type="button" value="Print" onclick="JavaScript:printPartOfPage('Div1');">

<script type="text/javascript">
<!--
function printPartOfPage(elementId)
{
 var printContent = document.getElementById(elementId);
 var windowUrl = 'about:blank';
 var uniqueName = new Date();
 var windowName = 'Print' + uniqueName.getTime();
 var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=0,height=0');

 printWindow.document.write(printContent.innerHTML);
 printWindow.document.close();
 printWindow.focus();
 printWindow.print();
 printWindow.close();
}
// -->
</script>

</form>

Http web request and response

Sample code


try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// add user-agent header to http request , and all works fine
                myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";

                // Sends the HttpWebRequest and waits for the response.
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                // Gets the stream associated with the response.
                if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
                {
                    Stream receiveStream = myHttpWebResponse.GetResponseStream();
                    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                    // Pipes the stream to a higher level stream reader with the required encoding format.
                    StreamReader readStream = new StreamReader(receiveStream, encode);
                    string response = "";
                    Char[] read = new Char[256];
                    // Reads 256 characters at a time.
                    int count = readStream.Read(read, 0, 256);


                    while (count > 0)
                    {
                        // Dumps the 256 characters on a string and displays the string to the console.
                        String str = new String(read, 0, count);
                        response += str;
                        //Console.Write(str);
                        count = readStream.Read(read, 0, 256);
                    }
                    // Releases the resources of the response.
                    myHttpWebResponse.Close();
                    // Releases the resources of the Stream.
                    readStream.Close();
                   
                }
                else
                {
                    return "";
                }

            }
            catch
            {

            }

How to reduce angular CLI build time

 Index: ----- I am using angular cli - 7 and I am going to tell how to reduce the build time as per my knowledge. Problem: -------- Now the ...