Wednesday, August 10, 2011

Generate Random Numbers using C#

Random randNum = new Random();
randNum.Next();

That's all it takes. The creation of a Random object (of the System.Random class) and calling its Next() method, which is going to return a non-negative random number as an integer.
EX:
Random randNum = new Random();
randNum.Next(108); // No larger than 108
randNum.Next(1, 108); // No larger than 108, no smaller than 1

Get the IP address in a Web/Windows application

using System.Net;
private void button1_Click(object sender, EventArgs e)
{

string myHost = System.Net.Dns.GetHostName();
string myIp = System.Net.Dns.GetHostEntry(myHost).AddressList[0].ToString();

richTextBox1.Text = (myHost);
richTextBox2.Text = (myIp);

}

Friday, August 5, 2011

Design Pattern (Abstract Factory Pattern) Hi Friends U can get help from this


Design Pattern (Abstract Factory Pattern)
Hi Friends U can get help from this
The intent of abstract factory Pattern is to provide interface of creating family of related or dependent object without specifying concert product class.
Let’s take example for developing web and windows application control. We have factory for Button controls having WebButton, WindowsButton and we have factory for TextBox control  WebTextBox, WindowsTextBox.  Now I want to create object for web or windows without specifying there concrete classes. In this situation I will use abstract factory.
The participant in the Abstract factory Pattern:
  • AbstractFactory: declare interface that create abstract product. In our example Application is AbstractFactory class.
  • ConcreteFactory: implement operation to create concrete product object. In our case webApplication and WindowApplication is ConcreteFactory
  • AbstractProduct: Declare interface for type of product. In our case control is Abstract product.
  • Product: define product which is created by correspondent ConcreteFactory. In our example Button and TextBox is Prroduct.
  • Client: use interface declare by abstractFactory and AbstractProduct classes.
Class Implementation
namespace FactoryPattern
{
      ///
      ///
Abstract Factory Class
      ///
      public abstract class MyApplicationFactory
      {
         public abstract MyButton CreateButton();
         public abstract MyTextBox CreateText();
      }
      ///
      ///
ConcreteFactory Class1
      ///
      public class WebFactory : MyApplicationFactory
      {
         public override MyButton CreateButton()
         {
            return new WebButton();
         }
         public override MyTextBox CreateText()
         {
            return new WebTextBox();
         }
      }
      ///
      ///
ConcreteFactory Class2
      ///
      public class WindowFactory : MyApplicationFactory
      {
         public override MyButton CreateButton()
         {
            return new WindowButton();
         }
         public override MyTextBox CreateText()
         {
            return new WindowTextBox();
         }
      }
      ///
      ///
Abstract product 1
      ///
      public abstract class MyButton
      
{
            public abstract void GetInformation();
      }
      ///
      ///
Abstract product 2
      ///
      public abstract class MyTextBox
      {
         public abstract void GetInformation();
      }
      ///
      ///
Product 1.1
      ///
      public class WebButton: MyButton
      {
         public override void GetInformation()
         {
            Console.Write("\nWebButton");
         }
      }
      ///
      ///
Product 1.2
      ///
      public class WindowButton : MyButton
      {
         public override void GetInformation()
         {
            Console.Write("\nWindowButton");
         }
      }
      ///
      ///
Product 2.1
      ///
      public class WebTextBox : MyTextBox
      {
         public override void GetInformation()
         {
            Console.Write("\nWebTextBox");
         }
      }
      ///
      ///
Product 2.2
      ///
      public class WindowTextBox : MyTextBox
      {
         public override void GetInformation()
         {
            Console.Write("\nWindowTextBox");
         }
      }
      ///
      ///
Client Class
      ///
      public class MyApplication
      {
         MyButton _button;
         MyTextBox _textbox;
         public MyApplication(MyApplicationFactory objFactory)
         {
            _button = objFactory.CreateButton();
            _textbox = objFactory.CreateText();
         }
         public void GetDetail()
         {
            _button.GetInformation();
            _textbox.GetInformation();
         }
      }
}

with thanks
RS Prajapati

SQL-Server 2008 R New Feature

Database Engine iconDatabase EngineThe Database Engine is the core service for storing, processing and securing data. The Database Engine provides controlled access and rapid transaction processing to meet the requirements of the most demanding data consuming applications within your enterprise. The Database Engine also provides rich support for sustaining high availability.
Analysis Services iconAnalysis Services - Multidimensional DataAnalysis Services supports OLAP by allowing you to design, create, and manage multidimensional structures that contain data aggregated from other data sources, such as relational databases.
Data mining iconAnalysis Services - Data MiningAnalysis Services enables you to design, create, and visualize data mining models. These mining models can be constructed from other data sources by using a wide variety of industry-standard data mining algorithms.
Integration Services iconIntegration ServicesIntegration Services is a platform for building high performance data integration solutions, including packages that provide extract, transform, and load (ETL) processing for data warehousing.
Master Data Services icon
Master Data Services Master Data Services is the source of master data for your organization. By integrating disparate operational and analytic systems with Master Data Services, you ensure that all applications across the organization rely on a central, accurate source of information. Using Master Data Services, you create a single source of master data and maintain an auditable record of that data as it changes over time.
Replication iconReplicationReplication is a set of technologies for copying and distributing data and database objects from one database to another, and then synchronizing between databases to maintain consistency. By using replication, you can distribute data to different locations and to remote or mobile users by means of local and wide area networks, dial-up connections, wireless connections, and the Internet.
Reporting Services iconReporting ServicesReporting Services delivers enterprise, Web-enabled reporting functionality so you can create reports that draw content from a variety of data sources, publish reports in various formats, and centrally manage security and subscriptions.
ms130214.SharePoint_icon(en-us,SQL.105).gif
SharePoint IntegrationSQL Server 2008 R2 offers new self-service business intelligence capability through integration with SharePoint products and technologies. In this release, both Analysis Services and Reporting Services support deployment in a SharePoint farm.
Service Broker iconService BrokerService Broker helps developers build scalable, secure database applications. This new Database Engine technology provides a message-based communication platform that enables independent application components to perform as a functioning whole. Service Broker includes infrastructure for asynchronous programming that can be used for applications within a single database or a single instance, and also for distributed applications.

Generate Dynamic Table ,Column by Using Cusor (Binging data for Gridview )

CREATE  PROC SP_FINAL_REPORT
(@SessionId int,@ClassId int,@Section varchar(2), 
 @TestTypeId int,@UserId varchar(40),@Criteria int 

/*-------------------------------
Writer :RS Prajapati
Profile:Software Engineer
Date: 05/08/2011
*/
AS BEGIN   
IF(@Criteria=1) 
BEGIN 
------------------------------------   
CREATE TABLE #TMP   
(   
ID INT NULL,SNAME VARCHAR(50) NULL   
)   
INSERT INTO #TMP EXEC sp_getacademicsubject @UserId,@SessionId,@ClassId ---'Devender',2,13   
--SELECT * FROM #TMP   
------------------------------------   
CREATE TABLE #TMP1   
(ROLLNO INT NULL,STUDENT_ID INT NULL,   
 STUDENT_NAME VARCHAR(50) NULL)   
   
DECLARE @SQL NVARCHAR(1000)   
DECLARE @COLS NVARCHAR(1000)    
DECLARE @SNAME VARCHAR(25)   
   
DECLARE CUR_SUB CURSOR FAST_FORWARD FOR   
SELECT SNAME FROM #TMP   
OPEN CUR_SUB   
FETCH NEXT FROM CUR_SUB INTO @SNAME   
 WHILE(@@FETCH_STATUS=0)   
 BEGIN   
  SET @COLS=@SNAME + ' ' + 'VARCHAR(5)'    
  SELECT  @SQL='ALTER TABLE #TMP1 ADD ' + @COLS   
  EXEC(@SQL)   
FETCH NEXT FROM CUR_SUB INTO @SNAME   
END   
 PRINT @sql 
 CLOSE CUR_SUB                                         
 DEALLOCATE CUR_SUB     
-------------------------------------   
DECLARE @SID INT   
DECLARE @LEN INT   
DECLARE @OBT_MARKS VARCHAR(5)   
DECLARE @GRADE VARCHAR(5)   
DECLARE @EVL_TYPE_ID INT   
DECLARE @STUDENTID VARCHAR(10)   
DECLARE @ROLLNO VARCHAR(5)    
DECLARE @STUDENT_NAME VARCHAR(50)   
SET @COLS=NULL   
SET @SQL=NULL   
   
DECLARE MAIN_CURSOR CURSOR FAST_FORWARD FOR   
  select distinct STM.Current_RollNo,SM._studentID,SM._studentname                     
  from tbl_StudentMaster SM INNER JOIN                      
  student_table_sessionwise STM on SM._studentID=STM.Student_Id                     
  where STM.SessionId=@SessionId and STM.Class=@ClassId  and STM.section=@Section                   
     
 OPEN MAIN_CURSOR    
 FETCH NEXT FROM MAIN_CURSOR INTO @ROLLNO,@STUDENTID,@STUDENT_NAME   
 WHILE (@@FETCH_STATUS=0)   
 BEGIN   
      ----------------------------------------------   
      DECLARE @COLL VARCHAR(2000) 
      SET @COLL=''   
      DECLARE EX_CURSOR CURSOR FAST_FORWARD FOR   
      SELECT ID FROM #TMP    
      OPEN EX_CURSOR    
      FETCH NEXT FROM EX_CURSOR INTO @SID   
      WHILE (@@FETCH_STATUS=0)   
      BEGIN   
              
        SELECT @OBT_MARKS=_OBT_MARKS,@GRADE=_GRADE,   
        @EVL_TYPE_ID=_EVL_TYPE_ID FROM    
        tbl_add_Marks_NS_KG WHERE  _academicId=@SessionId AND    
        _test_typeID=@TestTypeId AND _classID=@ClassId  AND    
        _studentId=@STUDENTID AND _subjectId=@SID   
        IF(@EVL_TYPE_ID=1)   
        begin   
        select @COLL=@COLL + ''''+@OBT_MARKS+''''+','   
        end   
        else   
        begin   
        select @COLL=@COLL + ''''+@GRADE+''''+','   
        end   
      
      SET @SID=NULL   
      FETCH NEXT FROM EX_CURSOR INTO @SID   
      END        
       
      SET @LEN=LEN(@COLL)   
      SET @COLL=SUBSTRING(@COLL,1,LEN(@COLL)-1) 
      SET @SQL='insert INTO #TMP1 VALUES('''+@ROLLNO+''','''+@STUDENTID+''','''+@STUDENT_NAME+''','+@COLL+')'   
      PRINT @SQL   
      EXEC(@SQL)   
      CLOSE EX_CURSOR                                         
      DEALLOCATE EX_CURSOR    
      --insert INTO #TMP1 VALUES(@ROLLNO,@STUDENTID,@STUDENT_NAME)   
      ----------------------------------------------   
   SET @ROLLNO=NULL     SET @STUDENTID=NULL             SET @STUDENT_NAME=NULL     
   FETCH NEXT FROM MAIN_CURSOR INTO @ROLLNO,@STUDENTID,@STUDENT_NAME     
   END   
   CLOSE MAIN_CURSOR                                         
   DEALLOCATE MAIN_CURSOR    
    
 SELECT * FROM #TMP1   
END   
END 

Merge Merging GridView Header Columns or multiple Headers ASP.NET C#

 
[GridHeader.JPG] 
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grvMergeHeader" runat="server"
BackColor="LightGoldenrodYellow"
BorderColor="Tan" BorderWidth="5px"
CellPadding="3" ForeColor="Black"
GridLines="None" BorderStyle="None"
CellSpacing="2"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
OnRowCreated="grvMergeHeader_RowCreated">
<FooterStyle BackColor="Tan" />
<SelectedRowStyle BackColor="DarkSlateBlue"
ForeColor="GhostWhite" />
<PagerStyle BackColor="PaleGoldenrod"
ForeColor="DarkSlateBlue"
HorizontalAlign="Center" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:BoundField DataField="DepartMentID"
HeaderText="DepartMentID"
SortExpression="DepartMentID" />
<asp:BoundField DataField="DepartMent"
HeaderText="DepartMent"
SortExpression="DepartMent" />
<asp:BoundField DataField="Name"
HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Location"
HeaderText="Location"
SortExpression="Location" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [DepartMentID],
[DepartMent], [Name], [Location] FROM [Employee]">
</asp:SqlDataSource>
&nbsp;</div>
</form>
</body>
</html>
============================================================================
Now In Code behind, in RowCreated Event of grid view i m creating a new gridview row of header type and than in this row i m adding 2 cells 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

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

}
protected void grvMergeHeader_RowCreated
(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView HeaderGrid = (GridView)sender;
GridViewRow HeaderGridRow =
new GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert);
TableCell HeaderCell = new TableCell();
HeaderCell.Text = "Department";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = "Employee";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

grvMergeHeader.Controls[0].Controls.AddAt
(0, HeaderGridRow);

}
}
}

Merge Merging GridView Header Columns or multiple Headers ASP.NET C#


Implementing Service Locator (To Resolve Dependency)

using System; /// <summary> /// Summary description for Class1 /// </summary> public class serviceLocator {     public s...