Resource Responses

Search Guest Response by Email:
Total 164 responses found.
Use VBA to Compare Data in a Text File with the List of Excel Worksheet
I am thankful to all visitors and editors of DotNetSpider . It is too useful article for newbie who want to know about how to use file system object.I am mentioning few more code snippet for Use VBA to Compare Data in a Text File as example of my articles for separator character

Sub DoTheImport()
Dim FName As Variant
Dim Sep As String
FName = Application.GetOpenFName(FileFilter:="Text File (*.txt),*.txt")
If FName = False Then
// code snippet to cencellout
Exit Sub
End If
Sep = Application.InputBox("Enter a separator character.", Type:=2)
If Sep = vbNullString Then
// code snippet to cencellout
Exit Sub
End If
Debug.Print "FName: " & FName, "Separator: " & Sep
ImportTextFile FName:=CStr(FName), Sep:=CStr(Sep)
End Sub

Author: Phagu Mahato      Posted Date: 01 Nov 2014
Wizard
Thanks to posting useful code snippet . But Dear Satya It is not running successfully in programm
Author: Phagu Mahato      Posted Date: 10 Aug 2014
Creating Custom Type Convertors in Silverlight
You can try this code snippet

The Product Class
public class Product {

public Product() { }

public Product(string name, decimal price,
bool onSpecial) {
this.ProductName = name;
this.Price = price;
this.IsOnSpecial = onSpecial;
}

public string ProductName { get; set; }
public decimal Price { get; set; }
public bool IsOnSpecial { get; set; }
}

Create a collection class that initializes a property called DataCollection with some sample data as shown in the code below:

public class Products : List {
public Products() {
InitCollection();
}

public List DataCollection { get; set; }

List InitCollection() {
DataCollection = new List();

DataCollection.Add(new Product(3,
"PDSA .NET Productivity Framework"), 5000, true));
DataCollection.Add(new Product(1,
"Haystack Code Generator for .NET", 799, true));
DataCollection.Add(new Product(1,
"Fundamentals of .NET eBook", 20, false));

return DataCollection;
}
}

Author: Phagu Mahato      Posted Date: 05 Mar 2014
DataTypes in C#
Thanks for sharing about datatype of C# . I also mansion about data type

C# Type .Net Framework Signed? Possible Values
sbyte System.Sbyte Yes -128 to 127
short System.Int16 Yes -32768 to 32767
int System.Int32 Yes -2147483648 to 2147483647
long System.Int64 Yes -9223372036854775808 to 9223372036854775807
byte System.Byte No 0 to 255
ushort System.Uint16 No 0 to 65535
uint System.UInt32 No 0 to 4294967295
ulong System.Uint64 No 0 to 18446744073709551615
float System.Single Yes ~ ±1.5 x 10-45 to ±3.4 x 1038 with 7 figures
double System.Double Yes ~ ±5.0 x 10-324 to ±1.7 x 10308 with 15 or 16 figures
decimal System.Decimal Yes ~ ±1.0 x 10-28 to ±7.9 x 1028 with 28 or 29 figures
char System.Char N/A Any Unicode character (16 bit)
bool System.Boolean N/A true or false


Author: Phagu Mahato      Posted Date: 04 Mar 2014
Select and Highlight an entire row in DataGridView
You can also try below code snippet

void dataGridView1_RowPrePaint(object sender,
DataGridViewRowPrePaintEventArgs e)
{
e.PaintParts &= ~DataGridViewPaintParts.Focus;
if ((e.State & DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected)
{
Rectangle rowBounds = new Rectangle(
this.dataGridView1.RowHeadersWidth, e.RowBounds.Top,
this.dataGridView1.Columns.GetColumnsWidth(
DataGridViewElementStates.Visible) -
this.dataGridView1.HorizontalScrollingOffset + 1,
e.RowBounds.Height);

using (Brush backbrush =
new System.Drawing.Drawing2D.LinearGradientBrush(rowBounds,
this.dataGridView1.DefaultCellStyle.SelectionBackColor,
e.InheritedRowStyle.ForeColor,
System.Drawing.Drawing2D.LinearGradientMode.Horizontal))
{
e.Graphics.FillRectangle(backbrush, rowBounds);
}
}
}

Author: Phagu Mahato      Posted Date: 04 Mar 2014
What are the authentication methods in .NET?
Authentication Methods :ASP. NET provides different methods to authenticate a user:

Certificate Authentication
Passport Authentication
Forms Authentication
Anonymous Authentication
Basic Authentication
Digest Authentication
Integrated Windows Authentication
Using Cookies

public string UseService (string Key, string ServiceName)
{
string [] HashArray;
string Uname, level;


HashArray=Key.Split('|');
level = "-1"; //default level

if (TestHash(HashArray[0], HashArray[1], 0, ServiceName))
{
try
{
Uname=HashArray[1];

switch (Uname)
{
case "MyUname":
level="1";
break;
case "OtherUser":
level="2";
break;
default:
level="-1";
break;
}
if (level=="1") return "YOU ARE AUTHORIZED";
}
catch (Exception exc)
{
return "Authentication failure: " + exc.ToString();
}
}
return "Authentication failure";
}

Author: Phagu Mahato      Posted Date: 02 Mar 2014
What is Webservices and how it works
You ca use below example code for Web.Config


behaviorConfiguration="returnFaults">

Author: Phagu Mahato      Posted Date: 02 Mar 2014
How to send selected data from one ListBox to another ListBox?
You can Add the following

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
ArrayList arraylist1 = new ArrayList();
ArrayList arraylist2 = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btn1_Click(object sender, EventArgs e)
{
lbltxt.Visible = false;
if (ListBox1.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox1.Items[i]))
{
arraylist1.Add(ListBox1.Items[i]);

}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox1.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
lbltxt.Visible = true;
lbltxt.Text = "Please select atleast one in Listbox1 to move";
}
}

protected void btn2_Click(object sender, EventArgs e)
{
lbltxt.Visible = false;
while(ListBox1.Items.Count!=0)
{
for(int i=0;i{
ListBox2.Items.Add(ListBox1.Items[i]);
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
}

protected void btn3_Click(object sender, EventArgs e)
{
lbltxt.Visible = false;
if (ListBox2.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
if (ListBox2.Items[i].Selected)
{
if (!arraylist2.Contains(ListBox2.Items[i]))
{
arraylist2.Add(ListBox2.Items[i]);
}
}
}
for (int i = 0; i < arraylist2.Count; i++)
{
if (!ListBox1.Items.Contains(((ListItem)arraylist2[i])))
{
ListBox1.Items.Add(((ListItem)arraylist2[i]));
}
ListBox2.Items.Remove(((ListItem)arraylist2[i]));
}
ListBox1.SelectedIndex = -1;
}
else
{
lbltxt.Visible = true;
lbltxt.Text = "Please select one in Listbox2 to move";
}
}

protected void btn4_Click(object sender, EventArgs e)
{
lbltxt.Visible = false;
while (ListBox2.Items.Count != 0)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
ListBox1.Items.Add(ListBox2.Items[i]);
ListBox2.Items.Remove(ListBox2.Items[i]);
}
}
}
}

Author: Phagu Mahato      Posted Date: 27 Feb 2014
Longitude or Latitude Convert "Degrees Minute Second" Format to "Decimal Degree" C# Example
 public class GeoAngle
{
public bool IsNegative { get; set; }
public int Degrees { get; set; }
public int Mins { get; set; }
public int Sec { get; set; }
public int MilliSec { get; set; }



public static GeoAngle FromDouble(double ExaDegree)
{

while (ExaDegree < -180.0) ExaDegree += 360.0;

while (ExaDegree > 180.0) ExaDegree -= 360.0;

var result = new GeoAngle();


result.IsNegative = ExaDegree < 0;
ExaDegree = Math.Abs(ExaDegree);


result.Degrees = (int)Math.Floor(ExaDegree);
var delta = ExaDegree - result.Degrees;


var Sec = (int)Math.Floor(3600.0 * delta);
result.Sec = Sec % 60;
result.Mins = (int)Math.Floor(Sec / 60.0);
delta = delta * 3600.0 - Sec;


result.MilliSec = (int)(1000.0 * delta);

return result;
}



public override string ToString()
{
var degrees = this.IsNegative
? -this.Degrees
: this.Degrees;

return string.Format(
"{0}° {1:00}' {2:00}\"",
degrees,
this.Mins,
this.Sec);
}



public string ToString(string format)
{
switch (format)
{
case "NS":
return string.Format(
"{0}° {1:00}' {2:00}\".{3:000} {4}",
this.Degrees,
this.Mins,
this.Sec,
this.MilliSec,
this.IsNegative ? 'S' : 'N');

case "WE":
return string.Format(
"{0}° {1:00}' {2:00}\".{3:000} {4}",
this.Degrees,
this.Mins,
this.Sec,
this.MilliSec,
this.IsNegative ? 'W' : 'E');

default:
throw new NotImplementedException();
}
}
}

Author: Phagu Mahato      Posted Date: 26 Feb 2014
Round up amount
Try this

using System;

public class Example
{
public static void Main()
{
double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
foreach (double value in values)
Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2));

}
}
Or

Public Function RoundUD(ByVal numD As Decimal, _
ByVal places As Integer, _
ByVal UorD As Boolean) As Decimal

'UorD - True = up, false = down
Dim dr As Decimal
Try
Dim r As Decimal = CDec(10 ^ (places + 1)) 'raise to places + 1
dr = Math.Truncate(r * numD)
If UorD Then 'no adjustment for down
'up
dr += 5
End If
dr = Math.Truncate(dr / 10) * 10
dr = dr / r
Catch ex As Exception
Stop
End Try
Return dr
End Function

Author: Phagu Mahato      Posted Date: 25 Feb 2014
Capture the form on the screen during runtime
You can try this code

internal void CaptureScreen()
{
Graphics g1 = CreateGraphics();
Image MyImage = new Bitmap(ClientRectangle.Width,
ClientRectangle.Height, g1);
Graphics g2 = Graphics.FromImage(MyImage);
IntPtr dc1 = g1.GetHdc();
IntPtr dc2 = g2.GetHdc();
BitBlt(dc2, 0, 0, ClientRectangle.Width,
ClientRectangle.Height, dc1, 0, 0, 13369376);
g1.ReleaseHdc(dc1);
g2.ReleaseHdc(dc2);
MyImage.Save(@"Captured.jpg", ImageFormat.Jpeg);
}
[System.Runtime.InteropServices.DllImportAttribute( "gdi32.dll")]
private static extern bool BitBlt(
IntPtr hdcDest,
int nXDest
int nYDest
int nWidth
int nHeight
IntPtr hdcSrc
int nXSrc
int nYSrc
Int32 dwRop
);

Author: Phagu Mahato      Posted Date: 25 Feb 2014
how to create shared assembly
You can try to use this code snippet

using System.IO;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
protected void Capture(object sender, EventArgs e)
{
string url = txtUrl.Text.Trim();
Thread thread = new Thread(delegate()
{
using (WB browser = new WB())
{
browser.ScrollBarsEnabled = false;
browser.AllowNavigation = true;
browser.Navigate(url);
browser.Width = 1024;
browser.Height = 768;
browser.DocumentCompleted += new WBDocumentCompletedEventHandler(DocumentCompleted);
while (browser.ReadyState != WBReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}

private void DocumentCompleted(object sender, WBDocumentCompletedEventArgs e)
{
WB browser = sender as WB;
using (Bitmap bitmap = new Bitmap(browser.Width, browser.Height))
{
browser.DrawToBitmap(bitmap, new Rectangle(0, 0, browser.Width, browser.Height));
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byte[] bytes = stream.ToArray();
imgScreenShot.Visible = true;
imgScreenShot.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
}
}
}

Author: Phagu Mahato      Posted Date: 24 Feb 2014
copy text to clipboard
 
Copy to ClipBoard Test








Copy to clipboard test..


Click here copy to clipboard





PasteYou text here.




Author: Phagu Mahato      Posted Date: 23 Feb 2014
Joins and its usages
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN return all rows from multiple tables where the join condition is met.

SELECT Orders.OrderID, Students.StudentName, Orders.OrderDate
FROM Orders
INNER JOIN Students
ON Orders.StudentID=Students.StudentID;

Different SQL JOINs

Before we continue with examples, we will list the types the different SQL JOINs you can use:

[1] INNER JOIN:
Returns all rows when there is at least one match in BOTH tables
[2] LEFT JOIN:
Return all rows from the left table, and the matched rows from the right table
[3] RIGHT JOIN:
Return all rows from the right table, and the matched rows from the left table
[4] FULL JOIN:
Return all rows when there is a match in ONE of the tables
[5]Outer join : You might want to include them in your results even if the chef didn't include ingredient details yet. To do this, we'll use an outer join.
Author: Phagu Mahato      Posted Date: 22 Feb 2014
Paging and Sorting a GridView in XAML
You can try this code snippet

namespace WPFApp
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private DataGridColumn currentSortColumn;

private ListSortDirection currentSortDirection;

public MainWindow()
{
InitializeComponent();
DataContext = this;
RefreshProducts();
}

private void ProductsDataGrid_Loaded(object sender, RoutedEventArgs e)
{
DataGrid dataGrid = (DataGrid)sender;

currentSortColumn = dataGrid.Columns.Where(c => c.SortDirection.HasValue).Single();
currentSortDirection = currentSortColumn.SortDirection.Value;
}

private void ProductsDataGrid_TargetUpdated(object sender, DataTransferEventArgs e)
{
if (currentSortColumn != null)
{
currentSortColumn.SortDirection = currentSortDirection;
}
}

private void ProductsDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
e.Handled = true;
string sortField = String.Empty;


switch (e.Column.SortMemberPath)
{
case ("Id"):
sortField = "Id";
break;
case ("Name") :
sortField = "Name";
break;
}

ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ?
ListSortDirection.Ascending : ListSortDirection.Descending;
bool sortAscending = direction == ListSortDirection.Ascending;
Sort(sortField, sortAscending);
currentSortColumn.SortDirection = null;
e.Column.SortDirection = direction;
currentSortColumn = e.Column;
currentSortDirection = direction;
}

public event PropertyChangedEventHandler PropertyChanged;

private ObservableCollection products;
private int start = 0;
private int itemCount = 5;
private string sortColumn = "Id";
private bool ascending = true;
private int totalItems = 0;
private ICommand firstCommand;
private ICommand previousCommand;
private ICommand nextCommand;
private ICommand lastCommand;

public ObservableCollection Products
{
get
{
return products;
}
private set
{
if (object.ReferenceEquals(products, value) != true)
{
products = value;
NotifyPropertyChanged("Products");
}
}
}

public ICommand FirstCommand
{
get
{
if (firstCommand == null)
{
firstCommand = new RelayCommand
(
param =>
{
start = 0;
RefreshProducts();
},
param =>
{
return start - itemCount >= 0 ? true : false;
}
);
}

return firstCommand;
}
}

Author: Phagu Mahato      Posted Date: 21 Feb 2014
How to create Slider in ASP.NET using AJAX?
Tou can try to use these code snippet also

<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>





Ajax SliderExtender - How to use SliderExtender in asp.net ajax




Ajax Control Toolkit Example: Using SliderExtender




ID="ScriptManager1"
runat="server"
>

ID="SliderExtender1"
runat="server"
TargetControlID="TextBox1"
BoundControlID="TextBox2"
Minimum="200"
Maximum="600"
>










ID="TextBox1"
runat="server"
>


ID="TextBox2"
runat="server"
ForeColor="Crimson"
Width="25"
>


ID="LinkButton1"
runat="server"
Text="Change Image Size"
ForeColor="DodgerBlue"
Font-Bold="true"
BorderColor="CornflowerBlue"
BorderWidth="1"
OnClick="LinkButton1_Click"
>





ID="Image1"
runat="server"
ImageUrl="~/Images/Example.jpg"
Width="200"
/>




Author: Phagu Mahato      Posted Date: 19 Feb 2014
Indexers
An indexer provides array-like syntax. It allows a type to be accessed the same way as an array.Example code as menion below
this [Parameter]

{

get

{

// Get codes goes here

}

set

{

// Set codes goes here

}

}



using System;

class Layout
{
string[] _values = new string[100];
public string this[int number]
{
get
{

if (number >= 0 && number < _values.Length)
{

return _values[number];
}

return "Error";
}
set
{

if (number >= 0 && number < _values.Length)
{

_values[number] = value;
}
}
}
}

class Program
{
static void Main()
{
MyMyLayout MyMyLayout = new MyMyLayout();
MyMyLayout[1] = "Frank Gehry";
MyMyLayout[3] = "I. M. Pei";


string value1 = MyMyLayout[1];
string value2 = MyLayout[3];
string value3 = MyLayout[10];



Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(value3);

}
}

Author: Phagu Mahato      Posted Date: 18 Feb 2014
Difference between Response.Redirect and Server.Transfer
Both “Server” and “Response” are objects of ASP.NET. Server.Transfer and Response.Redirect both are used to transfer a user from one page to another page

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 accros 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.It transfers current page request to another .aspx page on the same server.Server.Transfer is a server-side redirection technique that simply changes the code's "focus" on the web server to a new page. Server.Transfer is far more efficient than Response.Redirect when the target page resides on the same web server, because it avoids the extra roundtrip and uses only server resources for the redirection.

It preserves server resources and avoids the unnecessary roundtrips to the server.

It preserves Query String and Form Variables (optionally).

It doesn’t show the real URL where it redirects the request in the users Web Browser.

Response.Redirect() :client know the physical loation (page name and query string as well). Context.Items loses the persisitance when nevigate 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. Response.Redirect method is by far the simplest method of redirecting processing from a source page to a different destination or target page in the same or even across different applications. When the web server receives a request for redirection, it sends a response header to the client that causes the client to send a new request back to the server. In other words, a redirect causes two request/response cycles: one for the original and one for the new redirected request.
Response.Redirect() will send you to a new page, update the address bar and add it to the Browser History. On your browser you can click back.

It redirects the request to some plain HTML pages on our server or to some other web server.

It causes additional roundtrips to the server on each request.
Author: Phagu Mahato      Posted Date: 17 Feb 2014
How to insert, update and delete operations in gridview with using session?
You can use given code snippet for Insert,Edit,Update,Delete,Cancel and Print operations in Gridview using C#

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;

public partial class gridview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
GetData();
}
}

private void GetData()
{
SqlConnection con = new SqlConnection(@"Data Source=.\;AttachDbFilenm=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
SqlCommand cmd = new SqlCommand("select*from customer", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.Commandnm == "ins")
{
TextBox nm = (TextBox)GridView1.FooterRow.FindControl("TextBox2");
TextBox age = (TextBox)GridView1.FooterRow.FindControl("TextBox3");
TextBox Cnty = (TextBox)GridView1.FooterRow.FindControl("TextBox4");
SqlConnection con = new SqlConnection(@"Data Source=.;AttachDbFilenm=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;Max Pool Size=20; Connection Timeout=10;");
con.Open();
SqlCommand cmd = new SqlCommand("insert into customer values('" + nm.Text + "','" + age.Text + "','" + Cnty.Text + "')", con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Label1.Text = "Record inserted successfully....";
GetData();
}
}
else if (e.Commandnm == "up")
{
SqlConnection con2 = new SqlConnection(@"Data Source=.;AttachDbFilenm=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;Max Pool Size=20; Connection Timeout=10;");
con2.Open();
GridViewRow grid1 = (GridViewRow)((Button)e.CommandSource).NamingContainer;
Label sid = (Label)grid1.FindControl("lsid");
TextBox nm = (TextBox)grid1.FindControl("tnm");
TextBox age = (TextBox)grid1.FindControl("tage");
TextBox Cnty = (TextBox)grid1.FindControl("tCnty"); SqlCommand cmd = new SqlCommand("update customer set nm='" + nm.Text + "',age='" + age.Text + "',Cnty='" + Cnty.Text + "' where sid ='" + sid.Text + "'", con2);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Label1.Text = "Record Updated successfully....";
GetData();
}
}
else if (e.Commandnm == "del")
{
GridViewRow grid1 = (GridViewRow)((Button)e.CommandSource).NamingContainer;
SqlConnection con1 = new SqlConnection(@"Data Source=.;AttachDbFilenm=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;Max Pool Size=20; Connection Timeout=10;");
con1.Open();
Label sid = (Label)grid1.FindControl("lsid");
SqlCommand cmd = new SqlCommand("delete from customer where sid='" + sid.Text + "'", con1);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Label1.Text = "Record Deleted successfully....";
GetData();
}
}
else if (e.Commandnm == "del")
{
GridView1.EditIndex=-1;
GetData();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Response.Redirect("print.aspx");
}
}

Author: Phagu Mahato      Posted Date: 15 Feb 2014
Overview of SQL Server Integration Service
Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. SQL Server Integration Services (SSIS) is a tool that we use to perform ETL operations; i.e. extract, transform and load data. SSIS provides the ability to:

Retrieve data from just about any source
Perform various transformations on the data; e.g. convert from one type to another, convert to uppercase or lowercase, perform calculations, etc.
Load data into just about any source
Define a workflow
Creating SSIS packages with SQL Server Management Studio (SSMS)
Business Intelligence Development Studio (BIDS)
Creating a simple SSIS package in BIDS
Deploying SSIS packages
Executing SSIS packages
Author: Phagu Mahato      Posted Date: 15 Feb 2014
Dynamically add or delete a row when inputting data
Example of JavaScript code snippet for Dynamically add or delete a row


function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}


function insRow()
{
var x=document.getElementById('POITable').insertRow(1);
var c1=x.insertCell(0);
var c2=x.insertCell(1);
c1.innerHTML="Example1";
c2.innerHTML="Example2";
}

Or try another code


Width="700px" Height="200px" PopupHorizontalAlign="WindowCenter" PopupVerticalAlign="WindowCenter"
AllowResize="True">






















Author: Phagu Mahato      Posted Date: 13 Feb 2014
How to enable alphanumeric characters in a text box?

Code snippet for enable alphanumeric characters in a text box


private void textBox_KeyPress(object sender, KeyPressEventArgs e)

{

if (Char.IsLetterOrDigit(e.KeyChar)

||e.KeyChar == '\b')

{

e.Handled = false;

}

else

{

e.Handled = true;

}

}

Or another code snippet
Function Isnumber(ByVal KCode As String) As Boolean
Isnumber = True
If Not IsNumeric(KCode) And KCode <> ChrW(Keys.Back) And KCode <> ChrW(Keys.Enter) And KCode <> "."c And KCode <> ","c Then
Isnumber = False
MsgBox("Please Enter Numbers only", MsgBoxStyle.OkOnly)
End If

End Function

Author: Phagu Mahato      Posted Date: 12 Feb 2014
Use of exists condition
SQL Statements that use the SQL EXISTS Condition are very inefficient since the sub-query is RE-RUN for EVERY row in the outer query's table

UPDATE Product SET supplier_name = (SELECT customers.name FROM customers WHERE customers.customer_id = Product.supplier_id)
WHERE EXISTS (SELECT customers.name
FROM customers
WHERE customers.customer_id = Product.supplier_id);

Author: Phagu Mahato      Posted Date: 11 Feb 2014
Split and Merge Files
You can use this code for split amd marge file
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;
using System.IO;

namespace Splitfiles
{
public partial class Form1 : Form
{
public FileStream fs;
string mergeFolder;
public Form1()
{
InitializeComponent();
}
List Packets = new List();

//Merge file is stored in drive
string SaveFileFolder = @"c:\";

//Code Under Brows button:

private void brows_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.ShowDialog();
txtBrowsFile.Text = openFileDialog1.FileName;

fs = new FileStream(txtBrowsFile.Text, FileMode.Open, FileAccess.Read);
int FileLength = (int)fs.Length / 1024;
string name = Path.GetFileName(txtBrowsFile.Text);
}
catch (Exception ex)
{
lblSendingResult.Text = "EXCEPTION:" + ex;
}
}
//Code Under Split button:

private void btnSplit_Click(object sender, EventArgs e)
{
SplitFile(txtBrowsFile.Text, Convert.ToInt32(5));
listBox1.Items.Add(Packets[0].ToString());
listBox1.Items.Add(Packets[1].ToString());
listBox1.Items.Add(Packets[2].ToString());
listBox1.Items.Add(Packets[3].ToString());
listBox1.Items.Add(Packets[4].ToString());
}

public bool SplitFile(string SourceFile, int nNoofFiles)
{
bool Split = false;
try
{
FileStream fs = new FileStream(SourceFile, FileMode.Open, FileAccess.Read);
int SizeofEachFile = (int)Math.Ceiling((double)fs.Length / nNoofFiles);

for (int i = 0; i < nNoofFiles; i++)
{
string baseFileName = Path.GetFileNameWithoutExtension(SourceFile);
string Extension = Path.GetExtension(SourceFile);

FileStream outputFile = new FileStream(Path.GetDirectoryName(SourceFile) + "\\" + baseFileName + "." +
i.ToString().PadLeft(5, Convert.ToChar("0")) + Extension + ".tmp", FileMode.Create, FileAccess.Write);

mergeFolder = Path.GetDirectoryName(SourceFile);

int bytesRead = 0;
byte[] buffer = new byte[SizeofEachFile];

if ((bytesRead = fs.Read(buffer, 0, SizeofEachFile)) > 0)
{
outputFile.Write(buffer, 0, bytesRead);
//outp.Write(buffer, 0, BytesRead);

string packet = baseFileName + "." + i.ToString().PadLeft(3, Convert.ToChar("0")) + Extension.ToString();
Packets.Add(packet);
}

outputFile.Close();

}
fs.Close();
}
catch (Exception Ex)
{
throw new ArgumentException(Ex.Message);
}

return Split;
}

//Code Under Merge button:
//Files have been merged and saved at location C:\\"

private void btnMergeFile_Click(object sender, EventArgs e)
{
MergeFile(mergeFolder);
}

public bool MergeFile(string inputfoldername1)
{
bool Output = false;

try
{
string[] tmpfiles = Directory.GetFiles(inputfoldername1, "*.tmp");

FileStream outPutFile = null;
string PrevFileName = "";

foreach (string tempFile in tmpfiles)
{
string fileName = Path.GetFileNameWithoutExtension(tempFile);
string baseFileName = fileName.Substring(0, fileName.IndexOf(Convert.ToChar(".")));
string extension = Path.GetExtension(fileName);

if (!PrevFileName.Equals(baseFileName))
{
if (outPutFile != null)
{
outPutFile.Flush();
outPutFile.Close();
}
outPutFile = new FileStream(SaveFileFolder + "\\" + baseFileName + extension, FileMode.OpenOrCreate, FileAccess.Write);

}

int bytesRead = 0;
byte[] buffer = new byte[1024];
FileStream inputTempFile = new FileStream(tempFile, FileMode.OpenOrCreate, FileAccess.Read);

while ((bytesRead = inputTempFile.Read(buffer, 0, 1024)) > 0)
outPutFile.Write(buffer, 0, bytesRead);

inputTempFile.Close();
File.Delete(tempFile);
PrevFileName = baseFileName;

}

outPutFile.Close();
lblSendingResult.Text = "You Files have been merged and saved at location C:\\";
}
catch
{

}

return Output;

}
}
}

Author: Phagu Mahato      Posted Date: 10 Feb 2014
Check IP Range
You can apply this Method that gets IP address: ASP.NET, C#

using System;
using System.Web;

namespace WebApplication1
{
public class Global : HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{

HttpRequest request = base.Request;


string myaddress = request.UserHostAddress;


base.Response.Write(myaddress);


base.CompleteRequest();
}
}
}

Author: Phagu Mahato      Posted Date: 10 Feb 2014
Paging in LINQ
You can try to use this sample code for Paging in LINQ

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Collections.Generic;


namespace pinCodeObjects
{

{


private static readonly object ReadLock = new object();


private static List m_pinCodeInstance;
public static List pinCodeInstance
{
get
{

if (m_pinCodeInstance == null)
{
lock (ReadLock)
{
if (m_pinCodeInstance == null)
{
m_pinCodeInstance = LoadData();
}
}

}
return m_pinCodeInstance;
}
}


public static IEnumerable GetpinCodes(int ResultsPerPage, int PageNumber)
{

//number of records to skip
int skip = (PageNumber - 1) * ResultsPerPage;

//number of results per page.
int take = ResultsPerPage;

//execute Linq query for result set
IEnumerable result = (from pincodes in pinCodeInstance select pincodes).Skip(skip).Take(ResultsPerPage);

//return result
return result;
}


public static int SelectCount()
{
return (from pincodes in pinCodeInstance select pincodes).Count();
}


private static List LoadData()
{


List pinlist = new List();


System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ProgrammersJournal"].ConnectionString;

conn.Open();

try
{


SqlCommand cmd = new SqlCommand("pj_getallpincodes", conn);


using (System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{


pinlist.Add(new pinCode(reader.GetSqlString(0).ToString(), reader.GetSqlString(1).ToString(), reader.GetSqlString(2).ToString(), Convert.ToDecimal(reader.GetSqlString(3).ToString()), Convert.ToDecimal(reader.GetSqlString(4).ToString()), Convert.ToInt32(reader.GetSqlString(5).ToString()), Convert.ToInt16(reader.GetSqlString(6).ToString())));
}
}
}

catch (Exception ex)
{


throw new Exception(ex.Message);
}

finally
{


if (conn.State != ConnectionState.Closed)
{
conn.Close();
}

//instance is populated
//force garbage collection
GC.Collect();
GC.WaitForPendingFinalizers();

}

//return new instance of pin code collection
return pinlist;
}

private pinCodeCollection()
{

}

}


public class pinCode
{


private string m_pin;
public string pin
{
get { return m_pin; }
}


public string City
{
get { return m_City; }
}


private string m_State;
public string State
{
get { return m_State; }
}


private decimal m_Latitude;
public decimal Latitude
{
get { return m_Latitude; }
}


private decimal m_Longitude;
public decimal Longitude
{
get { return m_Longitude; }
}


private int m_TimeZone;
public int TimeZone
{
get { return m_TimeZone; }
}


private short m_Dst;
public short Dst
{
get { return m_Dst; }
}


public pinCode()
{

}

public pinCode(string pin, string city, string state, decimal latitude, decimal longitude, int timeZone, short dst)
{

this.m_pin = pin;
this.m_City = city;
this.m_State = state;
this.m_Latitude = latitude;
this.m_Longitude = longitude;
this.m_TimeZone = timeZone;
this.m_Dst = dst;

}

}
}

Author: Phagu Mahato      Posted Date: 09 Feb 2014
Tips to improve asp.net preformance
Performance can be a key factor in a successful Web site or project.I suggest following ways to work with ASP.NET pages and controls efficiently.
If your application does not use session state, disable it in the Web.config file as follows:

Page requests using session state internally use a ReaderWriterLock to manage access to the session state. For pages that only read session data, consider setting EnableSessionState to ReadOnly.
<%@ Page EnableSessionState="ReadOnly" . . .%>
Avoid unnecessary round trips to the server

If you develop custom server controls, consider designing them to render client script for some of their functionality

Use the Page object's IsPostBack property to avoid unnecessary processing

Leave buffering on unless you have a specific reason to turn it off

Use the Transfer method of the Server object or use cross-page posting to redirect between ASP.NET pages in the same application

Use cache api as much as possible it will decrease your server roundtrip and boost application performance. ASP.NET 2.0 or higher version provides functionality called sqlcachedependancy for your database caching
Author: Phagu Mahato      Posted Date: 09 Feb 2014
Validate Numeric value with negative and decimals using Javascript
This JavaScript function you can all in onkeypress event of the textbox and it will validate the user entered value in client side.
function allowNegativeNumber(e) 
{
var charCode = (e.which) ? e.which : event.keyCode
if (charCode > 31 && (charCode < 45 || charCode > 57 )) {
return false;
}
return true;

}
Jquery Validation
$(document).ready(function() {
$("#formID").validate({
rules: {
field_name: {
numericOnly:true
}
}
});
});

$.validator.addMethod('numericOnly', function (value) {
return /[0-9 ]/.test(value);
}, 'Please only enter numeric values (0-9)');

Author: Phagu Mahato      Posted Date: 08 Feb 2014
How to display FLASH Movie in HTML page
You can add this code snippet in your programming







Author: Phagu Mahato      Posted Date: 08 Feb 2014
Bind Checkbox column in Datagridview based on Datatable
To bind the DataGridView with data here, I have used a DataTable class to add rows and binding the DataGridView using DataSource property.


private void btn_load_Click(object sender, EventArgs e)

{

DataTable dt = new DataTable();

dt.Columns.Add("Select", System.Type.GetType("System.Boolean"));

dt.Columns.Add("Student No");

dt.Columns.Add("Student Name");

dt.Columns.Add("admission Date");

DataRow datarow1;

for (int i = 0; i <= 10; i++)

{

datarow1 = dt.NewRow();

datarow1["Select"] = false;

datarow1["Student No"] = 1000 + i;

datarow1["Student Name"] = "Student " + i;

datarow1["admission Date"] = DateTime.Now.ToString("dd/MM/yyyy");

dt.Rows.Add(datarow1);

}

dataGridView1.AllowUserToAddatarow1ows = false;

dataGridView1.AllowUserToDeleteRows = false;

dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

dataGridView1.DataSource = dt;

}

Author: Phagu Mahato      Posted Date: 06 Feb 2014
Convert gridview to excel sheet
First of all thank It is really a good Posting . You can also try this

System.IO.StringWriter Swrite = new System.IO.StringWriter();
HtmlTextWriter htwriter = new HtmlTextWriter(Swrite);
Response.AddHeader("content-disposition", "attachment; filename=Example.xls");
Response.ClearContent();

Response.AddHeader("content-disposition", attachment);

GridView1.RenderControl(htwriter);
Response.Write(Swrite.ToString());
Response.Flush();
Response.End();

Author: Phagu Mahato      Posted Date: 05 Feb 2014
Calculate age as years, month & days
You can also try below code snippet for Calculate Age

using System;
public class Age
{
public int Years;
public int Months;
public int Days;
public Age(DateTime BirthDay)
{
this.Count(BirthDay);
}
public Age(DateTime BirthDay, DateTime CurrentDay)
{
this.Count(BirthDay, CurrentDay);
}
public Age Count(DateTime BirthDay)
{
return this.Count(BirthDay, DateTime.Today);
}
public Age Count(DateTime BirthDay, DateTime CurrentDay)
{
if ((CurrentDay.Year - BirthDay.Year) > 0 ||
(((CurrentDay.Year - BirthDay.Year) == 0) && ((BirthDay.Month < CurrentDay.Month) ||
((BirthDay.Month == CurrentDay.Month) && (BirthDay.Day <= CurrentDay.Day)))))
{
int DaysInBirthDayMonth = DateTime.DaysInMonth(BirthDay.Year, BirthDay.Month);
int DaysRemain = CurrentDay.Day + (DaysInBirthDayMonth - BirthDay.Day);
if (CurrentDay.Month > BirthDay.Month)
{
this.Years = CurrentDay.Year - BirthDay.Year;
this.Months = CurrentDay.Month - (BirthDay.Month + 1) + Math.Abs(DaysRemain / DaysInBirthDayMonth);
this.Days = (DaysRemain % DaysInBirthDayMonth + DaysInBirthDayMonth) % DaysInBirthDayMonth;
}
else if (CurrentDay.Month == BirthDay.Month)
{
if (CurrentDay.Day >= BirthDay.Day)
{
this.Years = CurrentDay.Year - BirthDay.Year;
this.Months = 0;
this.Days = CurrentDay.Day - BirthDay.Day;
}
else
{
this.Years = (CurrentDay.Year - 1) - BirthDay.Year;
this.Months = 11;
this.Days = DateTime.DaysInMonth(BirthDay.Year, BirthDay.Month) - (BirthDay.Day - CurrentDay.Day);
}
}
else
{
this.Years = (CurrentDay.Year - 1) - BirthDay.Year;
this.Months = CurrentDay.Month + (11 - BirthDay.Month) + Math.Abs(DaysRemain / DaysInBirthDayMonth);
this.Days = (DaysRemain % DaysInBirthDayMonth + DaysInBirthDayMonth) % DaysInBirthDayMonth;
}
}
else
{
throw new ArgumentException("Birthday date must be earlier than current date");
}
return this;
}
}
Or another code as below

DateTime currentDate = DateTime.Now;

int Days = currentDate.Day - dateOfBirth.Day;
int Months = currentDate.Month - dateOfBirth.Month;
int Years = currentDate.Year - dateOfBirth.Year;

if (Days < 0)
{
Days += DateTime.DaysInMonth(currentDate.Year, currentDate.Month);
Months--;
}

if (Months < 0)
{
Months += 12;
Years--;
}

Console.WriteLine("Your Age: {0} years and {1} months and {2} days", Days, Months, Years);

Author: Phagu Mahato      Posted Date: 05 Feb 2014
Generate Random Image using Javascript
Thank for Posting article in Random Image using Javascript . You can also use this code snippet for it
 

SCRIPT language=JavaScript(Starting Script)
function swapImage() {
theImages = new Array("Myimage1.jpg", "Myimage2.jpg", "Myimage3.jpg");
whichImage = Math.floor(Math.random()*theImages.length);
document.write('');
}
/SCRIPT(Close script)





Or

/code]



Author: Phagu Mahato      Posted Date: 04 Feb 2014
Reading and writing files in C#.net

Example code for writing files in c Sharp


using System;
using System.IO;

namespace writeapp
{
class TextFileWriter
{
static void Main(stxtreading[] args)
{
Textxtwriteriter txtxtwriterite = new StxtreadeamWriter("Exampletest.txt");
txtwrite.WriteLine(DateTime.Now);
txtwrite.Close();
}
}
}

Reading From a Text File.



using System;
using System.IO;

namespace csharp_station.howto
{
class TextFileReader
{
static void Main(stxtreading[] args)
{

Textreader txtread = new StxtreadeamReader("Exampletest.txt");

Console.WriteLine(txtread.ReadLine());

txtxtreadead.Close();
}
}

Example of Reading and writing files in c Sharp.

using System;
using System.IO;

namespace FileHandlingReadandwrite
{
class Program
{
static void Main(stxtreading[] args)
{
if(File.Exists("Exampletest.txt"))
{
stxtreading Mycontent = File.ReadAllText("Exampletest.txt");
Console.WriteLine("Your Current content of file:");
Console.WriteLine(Mycontent);
}
Console.WriteLine("Enter content for the file:");
stxtreading newContent = Console.ReadLine();
File.WriteAllText("Exampletest.txt", newContent);
}
}
}
// code for append content
File.AppendAllText("Exampletest.txt", newContent);

Author: Phagu Mahato      Posted Date: 31 Jan 2014
Foundations of ASP.NET AJAX
ASP.NET AJAX is Microsoft’s solution to this problem. ASP.NET AJAX is a set of extensions to the existing ASP.NET 2.0 technology that provides you with a fast-and-simple environment to create Ajax applications. Microsoft has combined Ajax with ASP.NET technology and provided a unified set of development tools within Visual Studio 2005. For the first time, Ajax applications can be developed seamlessly in conjunction with a supporting technology.

Foundations of ASP.NET AJAX is written by Laurence Moroney, This book gives you a detailed grounding in how ASP.NET AJAX works. It takes you swiftly through the basic principles of Ajax, then deep into the heart of the technology, where every namespace is discussed and every function considered. By the end of the book, you will know all about the essentials to confidently produce cutting-edge ASP.NET AJAX applications swiftly and professionally. .
Author: Phagu Mahato      Posted Date: 31 Jan 2014
How to perform validation on the controls which is inside the Radgrid control?
Adding controls to a RadGrid template is easy enough, but sometimes we have to interact with them on the client, so that we save a roundtrip to the server. This project demonstrates how to get a reference to the DOM element of a server-side control on the client. The page has two client-side features: single select in a checkbox column; and selecting an item in a dropdown.Example code snppet as below

function checkboxClicked(e, idFragment)
{
var currentCheckBox = e.srcElement || e.target;
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++)
{
var input = inputs[i];

if (input.id == currentCheckBox.id)
continue;

if (input.id.indexOf(idFragment) < 0)
continue;

if (input.type && input.type == "checkbox")
{
input.checked = false;
}
}
}

Author: Phagu Mahato      Posted Date: 31 Jan 2014
Difference Between VB.Net and C#.Net
Thanks for posting useful Difference between C# and VB.NET . I also post more comparision between C# and VB.NET

Advantages VB.NET :-


It has support for optional parameters which makes COM interoperability much easy.
It is supported. Legacy VB functionalities can be
used by using Microsoft. Visual Basic name-space.
Has the WITH construct which is not in C#.
The VB.NET part of Visual Studio .NET compiles your code in the background.
While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.
Support for optional parameters - very handy for some COM interoperability.
Support for late binding with Option Strict off - type safety at compile time goes out of the window, but legacy libraries which don't have strongly typed interfaces become easier to use.
Support for named indexers.
Declaration of variable

Dim x As Integer
Public x As Integer = 10


Advantages of C#


Operator overloading which is not in current VB.NET but is been introduced in Whidbey.
The using statement, which makes unmanaged resource disposal simple.
Access to Unsafe code. This allows pointer arithmetic etc, and can improve
performance in some situations. However, it is not to be used lightly, as a lot of the
normal safety of C# is lost (as the name implies).This is the major difference that you
can access unmanaged code in C# and not in VB.NET.
XML documentation generated from source code comments.
Declaration of variable

int x;
int x = 10;

Author: Phagu Mahato      Posted Date: 30 Jan 2014
Dynamic Color Changing Background Using JavaScript

Code Snippet for Dynamic Color Changing Background Using JavaScript

You ca try below code snippet for







Colored cellColored cellColored cell



OR,

Or
function changeBackground(color) {
document.body.style.background = color;
}


Example of Javascript Change Background Color





Javascript Change Background Color Style










value="click here"
onclick="changeBackgroundColor('div1')" />



Author: Phagu Mahato      Posted Date: 28 Jan 2014
Anonymous Types in LINQ : A Step Ahead Series
Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence.Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid.

var vr = new { Fee = 108, Message = "Paid" };
Console.WriteLine(vr.Fee+ vr.Message);

The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.
var productQuery =  from prod in Schools
select new { prod.Color, prod.Price };

foreach (var v in SchoolQuery)
{
Console.WriteLine("Color={0}, Price={1}", v.Roll, v.Fee);
}
Anonymous types have been introduced to support one of the most useful features called LINQ. It's most useful when you are querying collection of object using LINQ query . Below example about Anonymous types easily by using new keyword of C#
var Phagu = new { id=1, Name= "Phagu Mahato" };
var Prem = new { id=1, Name= "Prem" };

Array of anonymously typed elements by combining an implicitly typed local variable and an implicitly typed array, as shown in the following example code snippet.

var Arraytype = new[] { new { name = "Mango", diam = 4 }, new { name = "Coconut", diam = 1 }};
 
Author: Phagu Mahato      Posted Date: 26 Jan 2014
How to Remove all the special characters from a Given String
You can use given code snippet for Remove all the special characters from a Given String

[1] Finding Special Character
public static string Slugify(string phrase)
{
String str = Regex.Replace(phrase, @"[^a-z0-9\s-]", " ");
str = Regex.Replace(str, @"\s+", " ").Trim();
return str;
}

For Replace Special Characters

public static string RemoveSpeCharacter(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}


protected void Button1_Click(object sender, EventArgs e)
{
string str=TextBox1.Text;
TextBox2.Text=RemoveSpelCharacter(str);
}
Or
using System;
using System.Text.RegularExpressions;

namespace eApplication3
{
class Program
{
static void Main(string[] args)
{
string str = "DotNet@Spider.com";
string replacestr= Regex.Replace(str, "[^a-zA-Z0-9_]+", " ");
Console.WriteLine(replacestr);
Console.ReadLine();
}
}
}

Author: Phagu Mahato      Posted Date: 25 Jan 2014
How to do Grid view sorting
Thank for posting useful article about Grid view sorting. Now I post some more sample code
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
listBindByName();
DataSet datasortTable = GridView1.DataSource as DataSet;
DataTable dtSortTable = datasortTable.Tables[0];
if (dtSortTable != null)
{
DataView dvSortedView = new DataView(dtSortTable);
dvSortedView.Sort = e.SortExpression + " " + getExamplesortDirectionString();
ViewState["sortExpression"] = e.SortExpression;
GridView1.DataSource = dvSortedView;
GridView1.DataBind();
}
UpdatePanel1.Update();
}

private string getExamplesortDirectionString()
{
if (ViewState["ExamplesortDirection"] == null)
{
ViewState["ExampleExamplesortDirection"] = "ASC";
}
else
{
if (ViewState["ExamplesortDirection"].ToString() == "ASC")
{
ViewState["ExamplesortDirection"] = "DESC";
return ViewState["ExamplesortDirection"].ToString();
}
if (ViewState["ExamplesortDirection"].ToString() == "DESC")
{
ViewState["ExamplesortDirection"] = "ASC";
return ViewState["ExamplesortDirection"].ToString();
}

Author: Phagu Mahato      Posted Date: 23 Jan 2014
Filtering data table using LINQ query
You can follow following Steps for
1.) You can use the DataTable.Select method. However, the results are an array of DataRow which is not bindable.
2.) You can use a DataView which is efficient for sorting, filtering. All DataTables have a default DataView -- DataTable.DefaultView
3.) Or you can use LINQ.
Sample code as below
DataView dv = new DataView(tableOne, "ProductID <> 'PDXX'", "ProductTime desc", DataViewRowState.CurrentRows);

Or transform the DataView back to a DataTable
DataTable newTable = new DataView(tableOne, "ProductID <> 'PDXX'",
"ProductTime desc", DataViewRowState.CurrentRows).ToTable();

Or you can use LINQ
IEnumerable Producted = tableOne.AsEnumerable()
.Where(i => i.Field("ProductID ") != 'PDXX')
.ProductByDescending(i => i.Field("ProductTime "));

Or use LINQ to transform it to a DataTable
DataTable newTable = tableOne.AsEnumerable()
.Where(i => i.Field("ProductID ") != 'PDXX')
.ProductByDescending(i => i.Field("ProductTime "))
.CopyToDataTable();

Author: Phagu Mahato      Posted Date: 22 Jan 2014
What is MSIL or CIL, What is JIT?

Some more useful Definition


MSIL stands for Microsoft Intermediate Language. We can call it as Intermediate Language (IL) or Common Intermediate Language (CIL). During the compile time , the compiler convert the source code into Microsoft Intermediate Language (MSIL) .Microsoft Intermediate Language (MSIL) is a CPU-independent set of instructions that can be efficiently converted to the native code
MSIL stands for Microsoft Intermediate Language and is also known as IL (Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to MSIL. This MSIL (Microsoft Intermediate Language) is then converted to machine code at the point where the software is installed, or at run-time by a Just-In- Time (JIT) compiler.
Author: Phagu Mahato      Posted Date: 21 Jan 2014
Interoperability

Introduction
The word ‘Interoperability’ really refers to the ability of diverse systems and organizations to work together . This term is often used in technical systems engineering cases also. In computer systems, there is lot of interaction happening between different new systems and old systems.The .NET Framework provides many great features including the Interoperability; it is achieved by set of tools and services provided by the framework. It includes a large library and supports several programming languages like C#, VB.NET etc. which allows language interoperability .The important goals of .NET during its development was to promote interoperability with existing technologies. .NET interoperability comes in three types:

Interoperability of .NET code with COM components
Interoperability of COM components with .NET
Interoperability of .NET code with Win32 DLLs
You can now interact with the COM object . Here is the code for the .NET class.


using System;
class Example
{
public static void Main()
{
private CHelloWorldClass Helloworld;
Helloworld = New CHelloWorldClass();
Console.WriteLine(Helloworld.sayHello("Hello, DNS"));
Console.ReadLine();
}
}


Author: Phagu Mahato      Posted Date: 20 Jan 2014
Scroll text in Status Bar
You can use this code snippet for Scroll text in Status Bar

function statusbar(val)
{
var massage = "Scrolling text";
var res = " ";
var speed = 100;
var Position = val;

if (position > 0) {
for (var Position=0 ; Position< position; Position++) {
res += " ";
}
res+=massage;
position--;
window.status = res;
timer = window.setTimeout("statusbar("+position+")",speed);
}
else{
if( -position < massage.length) {
res += massage.substring(-position,massage.length);
position--;
window.status=res;
timer = window.setTimeout("statusbar("+position+")",speed);
}
else
{
window.status= " ";
timer = window.setTimeout("statusbar(100)",speed);
}
}
}
statusbar(100);


//Another example

Be sure to edit the text that will scroll!


function scrollit(seed) {
var msg1 = "Code Snippet";
var msg2 = " To Scroll text ";
var msg3 = " In JavaScripts!";
var msg4 = "";
var msg=msg1+msg2+msg3+msg4;
var out = " ";
var c = 1;
if (seed > 100) {
seed--;
cmd="scrollit("+seed+")";
timerTwo=window.setTimeout(cmd,100);
}
else if (seed <= 100 && seed > 0) {
for (c=0 ; c < seed ; c++) {
out+=" ";
}
out+=msg;
seed--;
window.status=out;
cmd="scrollit("+seed+")";
timerTwo=window.setTimeout(cmd,100);
}
else if (seed <= 0) {
if (-seed < msg.length) {
out+=msg.substring(-seed,msg.length);
seed--;
window.status=out;
cmd="scrollit("+seed+")";
timerTwo=window.setTimeout(cmd,100);
}
else {
window.status=" ";
timerTwo=window.setTimeout("scrollit(100)",75);
}
}
}

Author: Phagu Mahato      Posted Date: 19 Jan 2014
What is ASP.NET?
It is a common question in ASP.
What is ASP.NET /
ASP.NET is a unified Web development model that includes the services necessary for you to build enterprise-class Web applications with a minimum of coding.ASP.NET offers you the following features:
  1. Web page design
  2. Page design features
  3. Code editing
  4. Testing and Debugging
  5. Deployment

The ASP.Net application codes could be written in either of the following languages:

C#

Visual Basic .Net

Jscript

J#
Sample language C#:

using System;
namespace Website
{
public partial class Examplecode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Hello, ASP world");
}
}
}


Sample language Visual Basic.NET:

Imports System
Namespace Website
Public Partial Class Examplecode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Response.Write("Hello, Asp world")
End Sub
End Class
End Namespace

Author: Phagu Mahato      Posted Date: 18 Jan 2014
Display Dynamic Date
Thanks for sharing code about display date



Display Current date in Web Page


current date is : <%= Date() %>.


Another program for display date , month and year








Author: Phagu Mahato      Posted Date: 18 Jan 2014
.NET interview questions for 5+ years of experience - OOPS, C#, WPF, .NET Fundamentals
What is a chain Constructor
Constructor Chaining is an approach where a Constructor calls another Constructor in the same or base class. Example of chain Constructor code snippet

namespace ConstructoreChaining

{

class A

{

public A(){

Console.WriteLine("ConstructorExampleExample A.");

}

public A(string s){

Console.WriteLine("ConstructorExample A with parameter = {0}",s);

}

public A(string s,string t){

Console.WriteLine("ConstructorExample A with parameter = {0} & {1}", s,t);

}

}



class B:A

{

public B():base(){

Console.WriteLine("ConstructorExample B.");

}

public B(string s):base(s){

Console.WriteLine("ConstructorExample B with parameter = {0}", s);

}

public B(string s, string t):base(s,t){

Console.WriteLine("ConstructorExample B with parameter = {0} & {1}", s, t);

}

}

class Program

{

static void Main(string[] args)

{

B b1 = new B();

B b2 = new B("First Parameter ", "Second Parameter");



Console.Read();

}

}

}



What is lambda expression in C#
A lambda expression is an anonymous Functionalist that you can use to create delegates or expression tree types.To create a lambda expression, you specify input parameters on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x . Example as below

using System.Linq.Expressions;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Expression del myET = x => x * x;
}
}

Program that uses lambda expressions: C#

using System;

class Program
{
static void Main()
{
Function Function1 = x => x + 1;
Function Function2 = x => { return x + 1; };
Functiontion Function3 = (int x) => x + 1;
Function Function4 = (int x) => { return x + 1; };
Function Function5 = (x, y) => x * y;
Action Function6 = () => Console.WriteLine();
Function Function7 = delegate(int x) { return x + 1; };
Function Function8 = delegate { return 1 + 1; };

Console.WriteLine(Function1.Invoke(1));
Console.WriteLine(Function2.Invoke(1));
Console.WriteLine(Function3.Invoke(1));
Console.WriteLine(Function4.Invoke(1));
Console.WriteLine(Function5.Invoke(2, 2));
Function6.Invoke();
Console.WriteLine(Function7.Invoke(1));
Console.WriteLine(Function8.Invoke());
}
}
}

Author: Phagu Mahato      Posted Date: 16 Jan 2014
Abstract Vs Interface
An interface cannot provide any code, just the signature.while An abstract class can provide complete, default code and/or just the details that have to be overridden.
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class

Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties


Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface An abstract class defines the core identity of a class and there it is used for objects of the same type.
Author: Phagu Mahato      Posted Date: 15 Jan 2014
SQL Basics
SQL stands for Structured Query Language.Two Types of SQL
DML ––Data Manipulation Language (SELECT)
DDL ––Data Definition Language (CREATE TABLE)

SQL Statements
The following SQL statement selects all the records in the "Examples" table:
SELECT * FROM Examples;
Most Important SQL Commands
  1. SELECT - extracts data from a database
  2. UPDATE - updates data in a database
  3. DELETE - deletes data from a database
  4. INSERT INTO - inserts new data into a database
  5. ALTER DATABASE - modifies a database
  6. CREATE TABLE - creates a new table
  7. ALTER TABLE - modifies a table
  8. DROP TABLE - deletes a table
  9. CREATE INDEX - creates an index
  10. DROP INDEX - deletes an index
  11. CREATE DATABASE - creates a new database


Pros & Cons of SQL



Pros:
Very flexible
Universal (Oracle, Access, Paradox, etc)
Relatively Few Commands to LearnRelatively Learn
Cons:
Requires Detailed Knowledge of the Structure of the Databaseof Database
Can Provide Misleading ResultsCan Results



Basic Structural Elements


  1. SELECT
  2. FROM
  3. WHERE
  4. ORDER BY
  5. GROUP BY

Selecting From Multiple TablesSelecting Tables


Join Multiple Tables via Primary and Foreign KeysJoin Keys
Aliases
Author: Phagu Mahato      Posted Date: 15 Jan 2014

    Next Results  


Top Contributors
Today
    Last 7 Daysmore...

    Awards & Gifts

    Online Members

    Gaurav Aroraa
    More...
     
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India