c-sharp-dot net-code offers c#.net Application Programming articales and csharp dot net tutorials, code examples in c# for download in pdf for free.
Thursday, 29 August 2013
Introduction to Microsoft .NET
Sunday, 19 February 2012
Console Output from a WinForms Application.
You may wish to enable your WinForms application to run from a console window or command line. And when it does, you probably want to send output messages to the console window that launched your WinForms application.
Unfortunately Console.WriteLine()–the standard method of writing to the console window–by default will not work from a WinForms application. That’s because the console window that launched your WinForms application belongs to the cmd.exe process, which is separate from your WinForms application process.
So to redirect output from a WinForms application to the console window that launched it, use the AttachConsole Win32 method introduced in Windows XP. AttachConsole attaches the current process to the console window of another process. The special parameter ATTACH_PARENT_PROCESS attaches to the parent process, which in this case is the console window that launched the WinForms application.
Simple Example
Following is a simple WinForms application that redirects its output to the console window that launched it:
using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace MyWinFormsApp { static class Program { [DllImport( "kernel32.dll" )] static extern bool AttachConsole( int dwProcessId ); private const int ATTACH_PARENT_PROCESS = -1; [STAThread] static void Main( string[] args ) { // redirect console output to parent process; // must be before any calls to Console.WriteLine() AttachConsole( ATTACH_PARENT_PROCESS ); // to demonstrate where the console output is going int argCount = args == null ? 0 : args.Length; Console.WriteLine( "nYou specified {0} arguments:", argCount ); for (int i = 0; i < argCount; i++) { Console.WriteLine( " {0}", args[i] ); } // launch the WinForms application like normal Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault( false ); Application.Run( new Form1() ); } } }
One Gotcha
There is one problem with this approach. If you redirect the console window output to a text file, for example using the redirect arrow:
MyWinFormsApp.exe >output.txt arg1 arg2
In this case, output will not redirect to the “output.txt” text file as expected, but instead will continue to appear in the console window. Please comment if you have a solution to this issue.
Show Continuous Progress with .NET ProgressBar and MarqueeAnimationSpeed
To make a ProgressBar cycle continuously, set the MarqueeAnimationSpeed property to a positive value (by default, it is set to 0). The value specifies the time period, in milliseconds, that it takes the progress block to scroll across the progress bar. A higher value results in a slower speed, and a lower value results in a faster speed. I’ve found that a value of 30 works pretty well. It’s also important to set the Style property to ProgressBarStyle.Marquee.
this.ProgressBar_Download.MarqueeAnimationSpeed = 30; this.ProgressBar_Download.Style = ProgressBarStyle.Marquee;To stop the cycle, set the Marquee Animation Speed property to 0. To resume the cycle, set it to a positive value.
Sunday, 5 February 2012
Jobs for .Net Freshers in Hyderabad.
Company Magna Infotech Pvt.Ltd
Website www.magna.in
Eligibility B.E/B.Tech, MCA
Experience 2-4 Years
Location Hyderabad
Magna Infotech Pvt.Ltd
Job Role: Software Engineer/ Programmer - .Net Developer With 2-4 years Exp
Job Summary:Ability to come out with good technical solutions
Ability to troubleshoot critical technology issues
Good knowledge of App server, Web server, DB server tuning
Knowledge of at least one Code profiling tools
Ability to guide team on technology
C# 2008 and the NET 3.5 Platform
This book has existed (in one form or another) since the first edition of C# and the .NET Platform
was published in conjunction with the release of .NET 1.0 Beta 2, circa the summer of 2001. Since
that point, I have been extremely happy and grateful to see that this text was very well received by
the press and, most important, by readers. Over the years it was nominated as a Jolt Award finalist
(I lost . . . crap!) and for the 2003 Referenceware Excellence Award in the programming book category
(I won? Cool!).
Since that point, I have worked to keep the book current with each release of the .NET platform,
including a limited printing of a Special Edition, which introduced the technologies of .NET 3.0
(Windows Presentation Foundation, Windows Communication Foundation, and Windows Workflow
Foundation) as well as offered previews of several forthcoming technologies, which we now know as
LINQ.
The fourth edition of this text, which you hold in your hands, is a massive retelling of the previous
manuscript to account for all of the major changes that are found within .NET 3.5. Not only will
you find numerous brand-new chapters, you will find many of the previous chapters have been
expanded in great detail.
As with the earlier editions, this edition presents the C# programming language and .NET base
class libraries using a friendly and approachable tone. I have never understood the need some
technical authors have to spit out prose that reads more like a GRE vocabulary study guide than a
readable book. As well, this new edition remains focused on providing you with the information you
need to build software solutions today, rather than spending too much time examining esoteric
details that few individuals will ever actually care about.
Download this book here.
Fibonacci Numbers
Program to print Fibonacci Numbers below 100.
using System;
class myclass
{
static void Main()
{
int fn = 0;
int sn = 1;
int tn = 1;
Console.WriteLine(fn);
Console.WriteLine(sn);
while (true)
{
tn = fn + sn;
if (tn >= 100)
{
break;
}
Console.WriteLine(tn);
fn = sn;
sn = tn;
}
Console.Read();
}
}
Output
0
1
1
2
3
5
8
13
21
34
55
89
Random Password Genrater
This Program takes input a string and generate random passwords using that string.
using System;
namespace randomPassword
{
class Program
{
static void Main(string[] args)
{
// Gets the length of the password.
int len;
// Gets the type of the password
int sel;
// Gets a random value.
int rand;
// The string that contains the password.
string pass = "";
// Random number.
Random num = new Random();
// Get the password length (user input).
Console.WriteLine("Password length:");
len = Convert.ToInt32(Console.ReadLine());
// Get the password type (user input).
Console.WriteLine("Select password type:");
Console.WriteLine("1 - Letters, Symbols, Numbers");
Console.WriteLine("2 - Letters, Symbols");
Console.WriteLine("3 - Letters, Numbers");
Console.WriteLine("4 - Letters");
Console.WriteLine("5 - Numbers");
sel = Convert.ToInt32(Console.ReadLine());
// Based on the password type, generate a password.
switch (sel)
{
// Complex password (letters, numbers, symbols).
case 1:
for (int c1 = 0; c1 < len; c1++)
pass += char.ConvertFromUtf32(num.Next(33, 126));
break;
// Password composed of letters and symbols.
case 2:
for (int c1 = 0; c1 < len; c1++)
{
genNew:rand = num.Next(33, 126);
if ((rand < 48) || (rand > 57))
{
pass += char.ConvertFromUtf32(rand);
}
else
{
goto genNew;
}
}
break;
// Password composed of letters and numbers.
case 3:
for (int c1 = 0; c1 < len; c1++)
{
genNew2:
rand = num.Next(33, 126);
if (((rand > 47) && (rand < 58)) || ((rand < 122) && (rand > 96)) || ((rand < 89) && (rand > 64)))
{
pass += char.ConvertFromUtf32(rand);
}
else
{
goto genNew2;
}
}
break;
// Password composed of letters.
case 4:
for (int c1 = 0; c1 < len; c1++)
{
genNew3:
rand = num.Next(33, 126);
if (((rand > 65) && (rand < 90)) || ((rand < 122) && (rand > 96)))
{
pass += char.ConvertFromUtf32(rand);
}
else
{
goto genNew3;
}
}
break;
// Password composed of numbers.
case 5:
for (int c1 = 0; c1 < len; c1++)
{
pass += char.ConvertFromUtf32(num.Next(48, 57));
}
break;
}
// Show the generated password.
Console.WriteLine("Your password is: {0}", pass);
Console.ReadLine();
}
}
}
WinApp - Click Counter
Code for the program is as follows:-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace clickcount
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int clickcount = 0;
private void button1_Click(object sender, EventArgs e)
{
clickcount++;
label1.Text = "number of clicks: " + clickcount + ".";
}
}
}
Write a C-Sharp .NET console application program for finding factorial of the given number.
Program source code for finding factorial of the given number in C#.NET.
using System;
using System.Collections.Generic;
using System.Text;
namespace factorial
{
class Program
{
static void Main(string[] args)
{
int i, fact = 1, n;
String no;
Console.WriteLine("Enter a number:");
no = Console.ReadLine();
n = Convert.ToInt32(no);
for (i = 1; i <= n; i++)
{
fact = fact * i;
}
Console.WriteLine("factorial is:" + fact);
Console.ReadLine();
}
}
}
Write a C-Sharp .NET Console program to generate the following number pattern.
Write a C-Sharp .NET Console program to generate the following number pattern.
1
22
333
4444
55555
Program Code:-
public class ForLoop{
public static void main(String[] args){
for(int i = 1;i <= 5;i++){
for(int j = 1;j <= i;j++){
System.out.print(i);
}
System.out.println();
}
}
}
Output of the program :
1
22
333
4444
55555
Thursday, 27 October 2011
c-sharp dot net code for tricky game using some mouse events
Saturday, 22 October 2011
c# ASP.NET Interview Questions And Answers Part-2
ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables and select insert and updates to the database. I can update the actual database as a batch.
C#
Client-side validation because there is no need to request a server side date when you could obtain a date from the client machine.
Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip (as in the datagrid example in tip #4), then you do not need the control to maintain it’s view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false.
Why would I choose one over the other? Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist across the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive. Response.Dedirect() :client know the physical location (page name and query string as well). Context.Items loses the persistence when navigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they’re difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.
When to Use Web Services:
* Communicating through a Firewall When building a distributed application with 100s/1000s of users spread over multiple locations, there is always the problem of communicating between client and server because of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly from a Windows UI is a very valid option.
* Application Integration When integrating applications written in various languages and running on disparate systems. Or even applications running on the same platform that have been written by separate vendors.
* Business-to-Business Integration This is an enabler for B2B integration which allows one to expose vital business processes to authorized supplier and customers. An example would be exposing electronic ordering and invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically.
* Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary component-based reuse. The limiting factor here is that you can reuse the code but not the data behind it. Webservice overcome this limitation. A scenario could be when you are building an app that aggregates the functionality of several other Applications. Each of these functions could be performed by individual apps, but there is value in perhaps combining the multiple apps to present a unified view in a Portal or Intranet.
* When not to use Web Services: Single machine Applications When the apps are running on the same machine and need to communicate with each other use a native API. You also have the options of using component technologies such as COM or .NET Components as there is very little overhead.
* Homogeneous Applications on a LAN If you have Win32 or Winforms apps that want to communicate to their server counterpart. It is much more efficient to use DCOM in the case of Win32 apps and .NET Remoting in the case of .NET Apps.
In ADO, the in-memory representation of data is the RecordSet. In ADO.NET, it is the dataset. There are important differences between them.
* A RecordSet looks like a single table. If a recordset is to contain data from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables into a single result table. In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple DataTable objects. That is, each DataTable object typically corresponds to a single database table or view. In this way, a dataset can mimic the structure of the underlying database. A dataset usually also contains relationships. A relationship within a dataset is analogous to a foreign-key relationship in a database —that is, it associates rows of the tables with each other. For example, if a dataset contains a table about investors and another table about each investor’s stock purchases, it could also contain a relationship connecting each row of the investor table with the corresponding rows of the purchase table. Because the dataset can hold multiple, separate tables and maintain information about relationships between them, it can hold much richer data structures than a recordset, including self-relating tables and tables with many-to-many relationships.
* In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. DataRelation objects maintain information about master and detail records and provide a method that allows you to get records related to the one you are working with. For example, starting from the row of the Investor table for "Nate Sun," you can navigate to the set of rows of the Purchase table describing his purchases. A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object. For more information about cursor functionality, see Data Access Technologies.
* Minimized Open Connections: In ADO.NET you open connections only long enough to perform a database operation, such as a Select or Update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the recordset can provide disconnected access, but ADO is designed primarily for connected access. There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source. The important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database — by optimizing for performance, performing data validation checks, or adding any other extra processing. Data adapters, data connections, data commands, and data readers are the components that make up a .NET Framework data provider. Microsoft and third-party providers can make available other .NET Framework data providers that can be integrated into Visual Studio.
* Sharing Data Between Applications. Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream.
* Richer data types.COM marshalling provides a limited set of data types — those defined by the COM standard. Because the transmission of datasets in ADO.NET is based on an XML format, there is no restriction on data types. Thus, the components sharing the dataset can use whatever rich set of data types they would ordinarily use.
* Performance. Transmitting a large ADO recordset or a large ADO.NET dataset can consume network resources; as the amount of data grows, the stress placed on the network also rises. Both ADO and ADO.NET let you minimize which data is transmitted. But ADO.NET offers another performance advantage, in that ADO.NET does not require data-type conversions. ADO, which requires COM marshalling to transmit records sets among components, does require that ADO data types be converted to COM data types.
* Penetrating Firewalls.A firewall can interfere with two components trying to transmit disconnected ADO recordsets. Remember, firewalls are typically configured to allow HTML text to pass, but to prevent system-level requests (such as COM marshalling) from passing.
The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It’s a good place to initialize global variables. For example, you might want to retrieve a list of products from a database table and place the list in application state or the Cache object. SessionStateModule exposes both Session_Start and Session_End events.
If I’m developing an application that must accomodate multiple security levels though secure login and my ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users?
By using Abstract classes/functions.

