Pages

Aug 13, 2009

How to generate a random unique 5 digit number + C#

Below is the method used to generate random 5 digit number.

public int getRandomID ()

{

Random r = new Random()

return r.Next(10000,99999);

}

The number 10000, 99999 specifies the range.

Aug 12, 2009

How to find and remove Special Characters from a given string. + C#

Here is the method which can remove all the special characters from a given stirng

public string RemoveSpecialChars(string str)
{
string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";", "-", "_", "(", ")", ":", "", "[", "]" };
for (int i = 0; i < chars.Length; i++)
{
if (str.Contains(chars[i]))
{
str = str.Replace(chars[i], "");
}
}
return str;
}


Thanks
Mukunda

May 1, 2009

Useful Links

1 JavaScript

1.1 How to get client date and time

1.2 How to access a control by using JavaScript

1.3 How to invoke a server-side function with JavaScript

1.4 How to retrieve server side variables using JavaScript code

1.5 How to assign a value to a hidden field using JavaScript in ASP.NET

1.6 How to register the JavaScript function at Code-Behind

1.7 How to display images with a delay of five seconds

1.8 How to get browser screen settings and apply it to page controls

1.9 How to clear the session when the user closes a window

2 Ways to pass data between pages

2.1 How to use cookies

2.2 How to use QueryString

2.3 How to use Session

2.4 How to use Context

2.5 How to use PreviousPage

2.6 How to use Submit Form

2.7 How to use Server.Transfer

3 File Upload

3.1 How to upload a file

3.2 How to upload multiple files at once

3.3 Why upload fails when using an ASP.NET FileUpload control to upload large files

3.4 How to upload an image files only

3.5 How to get a File Upload control work with an UpdatePanel

4 Calendar

4.1 How to change the culture settings for a Calendar

4.2 How to select multiple non-sequential dates at Code-Behind

4.3 How to disable some dates in Calendar control

4.4 How to extend Calendar control for Server-Side validation

4.5 How to set ToolTips and links in Calendar control’s DayRender event

4.6 How to give some dates different appearances

5 List controls

5.1 How to enable ASP.NET DropDownList with OptionGroup support

5.2 How to disable an item in DropDownList

5.3 How to hold the selected value for a DropDownList

6 User control

6.1 How to add a new property to UserControl

6.2 How to access a dynamically created UserControl

6.3 How to access a control inside a UserControl

7 Dynamic controls

7.1 How to create a dynamic control

7.2 How to access a user entered value in a dynamic created TextBox control

7.3 Dynamic controls accessed by JavaScript

7.4 How to retain all added server controls dynamically after post back

7.5 Why dynamically created controls disappear after a post back

8 Style

8.1 How to use with Code-Behind

8.2 How to use with JavaScript

8.3 How to remove a space

8.4 How to use with html

8.5 How to set an image as Button’s background

8.6 How to color items in ListBox

9 Print

9.1 How to print a part of a web page with CSS

9.2 How to print a part of a web page with JavaScript (1)

9.3 How to print a part of a web page with JavaScript (2)

10 Mail

10.1 What classes are needed to send e-mails in ASP.NET

10.2 How to send emails by using System.Net.Mail

10.3 How to configure a SMTP Server

10.4 How to send an email with Gmail server

How to Select the Asp.Net server controls + JQuery

People while using MasterPages in your applications client ID of controls will differ from "server" ID. That's because ASP.NET creates a new ID for controls on a page. So this is probably very familiar to you:

ctl00_cphContent_txtName

You set the ID of the textbox to "txtName" and ASP.NET adds "ctl00_cphContent_". Although there were some tries to prevent ASP.NET from generating unique ID's, I think it's better to use quick and "dirty" solutions :-)

So, how to select a server control using JS/jQuery? The usual way to select an element in JavaScript is to use server tags:

document.getElementById("<%=txtName.ClientID %>");

You can use the same approach with jQuery:

$("#'<%=txtName.ClientID %>'");

JQuery enables you to avoid server tags completely. Since we can search for element just by the part of the name, we can do the next:

$("[id$='_txtName']");

This will find elements which id's ends with "_txtName". But why the dash in the front of the name? This will ensure you selected the element by its full control ID, not just a part of it.

Pretty simple, isn't it? The only issue here would be if you have controls with the same name placed in different content pages.

How to access Page's session variable or create a new session variable in a normal C# class

This is Quite simple,
Usually

1 . We have lot of classes in the web application where the have the need to maintain or access the page's data or the server controls data between classes.
2. And there may be a situation where we need to send the data to the UI Page from the AppCode class or any class. For eg: i have processed something and need to send the data to the textbox in the UI Page.

This would be achieved by using
namespace
System.web.UI.;

And like this you can create a session variable in a non UI class and access it in the page's class.

HttpContext.Current.Session["test1"] = "Got from test";

and the same way you can access the page's session variable in the non UI class like

string test = string.Empty;
test = HttpContext.Current.Session["test1"].ToString();


Thus we can maintain the data between the classes no matter whether it is UI or normal class.


Apr 21, 2009

how to convert decimal degrees to miles + Javascript

To convert the decimal degrees to miles :

function distanceConverter(x1,y1,x2,y2)
{

// distance between 2 points from decimal degrees to miles
// where x values represent longitude
// where y values represent latitiude
dx = 69.172 * (x2 - x1) * Math.cos( y1 / 57.3);
dy = 69.172 * (y2 - y1);
var dist = Math.sqrt(dx * dx + dy * dy);
return dist;
}

Apr 14, 2009

how to display map co-ordinates for the mouse position + Mapextreme

          1. Add this line to public MapForm1():
mapControl1.MouseMove += new MouseEventHandler(MapControl1_MouseMove);
          2. Add this function to the project:
public void MapControl1_MouseMove(object sender, MouseEventArgs e)
{
System.Drawing.PointF DisplayPoint = new PointF(e.X,e.Y);
MapInfo.Geometry.DPoint MapPoint = new MapInfo.Geometry.DPoint();

MapInfo.Geometry.DisplayTransform converter = this.mapControl1.Map.DisplayTransform;
converter.FromDisplay(DisplayPoint, out MapPoint);

this.statusBar1.Text = "Cursor Location: " + MapPoint.x.ToString() + ", " + MapPoint.y.ToString();
}

This will display the current coordinates of the mouse position.

useful links for custom selection tools:

http://testdrive.mapinfo.com/techsupp/miprod.nsf/kbase_by_product/A5FA9134EB660E5A85256FB2005ABD17

http://community.mapinfo.com/forums/message.jspa?messageID=50295
http://testdrive.mapinfo.com/techsupp/miprod.nsf/kbase_by_product/A5FA9134EB660E5A85256FB2005ABD17
http://testdrive.mapinfo.com/techsupp/miprod.nsf/kbase_by_product/89C695CE5F2FAB4185256F0F005873BF

Apr 13, 2009

How to set the position of the Asp.Net control at runtime

The LEFT and TOP attributes in the following code sets the left and top positions of a control. You can call this code from any where in your code.

For example, if I have a table or calender control and want to change the position of the control dynamically, this is the code I need to add.

Calendar1.Attributes.Item("style") = "Z-INDEX: 176; LEFT: 334px; POSITION: absolute; TOP: 176px"

And in Asp.Net 3.5 it would be

Calendar1.Attributes.CssStyle.Value = "Z-INDEX: 176; LEFT: 334px; POSITION: absolute; TOP: 176px";


Apr 7, 2009

How to change the cursor style when mouse moves over the server controls

How to change the cursor style when mouse moves over the server controls :

Just we can set the cursor style on onmouseover and onmouseout events for any server controls like button, label textboxes etc.. as given below.

Open Triangle
asp:Button ID="Button1" runat="server" Text="" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'" style="cursor:pointer"
BorderStyle="None"
Close Triangle

Mar 16, 2009

Sending Email using C# and ASP.Net 2.0

Sending a Simple Mail Using GMail SMTP SERVER :

Use the namespace

using
System.Web.Mail;

MailMessage mail = new MailMessage();

mail.To.Add("to@gmail.com");

mail.From = new MailAddress("from@gmail.com");

mail.Subject = "Test Email";

string Body = "Welcome to Mukund's Blog";

mail.Body = Body;

mail.IsBodyHtml = true;

SmtpClient smtp = new SmtpClient();

smtp.Host = ConfigurationManager.AppSettings["SMTP"];

smtp.Credentials = new

System.Net.NetworkCredential(ConfigurationManager.AppSettings["FROMEMAIL"],

ConfigurationManager.AppSettings["FROMPWD"]);

smtp.EnableSsl = true;

smtp.Send(mail);

The above code can be used to send a simple email.


Sending Mail with Attachment:

MailMessage mail = new MailMessage();

mail.To.Add("to@gmail.com");

mail.From = new MailAddress("From@gmail.com");

mail.Subject = "Test Email";

string Body = "Welcome to Mukund's Blog";

mail.Body = Body;

mail.Attachments.Add(new Attachment(@"F:\Articles\Email in ASP.Net 2.0\SendEmail\mail.png"));

SmtpClient smtp = new SmtpClient();

smtp.Host = ConfigurationManager.AppSettings["SMTP"];

smtp.Send(mail);


The webcongif file should contain the following code.

Add open triangle and close triangle braces for each tag.

appSettings

add key="SMTP" value="smtp.gmail.com"

add key="FROMEMAIL" value="mail@gmail.com"

add key="FROMPWD" value="password"

appSettings

The above code can be used to send a simple email with attachment.

Dec 30, 2008

SharePoint

SharePoint:
What Is SharePoint?
SharePoint Facts
Why Should You Use SharePoint?
Microsoft Office SharePoint Server 2007
Windows SharePoint Services 3.0
Which SharePoint Technology Is Right For You?
MOSS 2007
Top 10 Benefits of Windows SharePoint Services

What is SharePoint?
SharePoint is an enterprise information portal, from Microsoft, that can be configured to run Intranet, Extranet and Internet sites. Microsoft Office SharePoint Server 2007 allows people, teams and expertise to connect and collaborate. A SharePoint enterprise portal is composed of both SharePoint Portal and Windows SharePoint Services, with SharePoint being built upon WSS. WSS is typically used by small teams, projects and companies. SharePoint Server is designed for individuals, teams and projects within a medium to large company wide enterprise portal.


Some SharePoint facts
• SharePoint is the fastest-growing product in the history of Microsoft
• Over 75 million licenses of SharePoint have been sold worldwide
• SharePoint is listed, by Forrester, as the number 1 portal product
• SharePoint is positioned as a leader within the Gartner Magic Quadrant for Horizontal Portals products
• Over 400 case studies have been published on SharePoint

Why should you use SharePoint?
SharePoint solves four main problems:

• As companies grow so does the amount of their files. It soon becomes difficult to keep track of the multiplying documents and their locations. SharePoint overcomes this by allowing you to store and locate your files in a central site. Files can also be located through company wide searches of your SharePoint enterprise portal.

• Sharing work files through email is a cumbersome process. SharePoint eliminates this by allowing files to be stored in one location, allowing easy access to all team members.

• Today’s work occurs over multiple locations, whether it is in different countries, office locations, separate departments or at your home office. SharePoint enables teams and individuals to connect and collaborate together regardless of where they are located.

• It’s difficult and time consuming to create and maintain sites. SharePoint allows anyone to create sites for use within their company’s Intranet, as they are needed, whether they are departmental sites, document libraries, meetings sites, survey sites, or discussion boards.

Microsoft Office SharePoint Server 2007:

Microsoft Office SharePoint Server 2007 is a collaborative enterprise portal that is built upon WSS 3.0. MOSS 2007 allows people, teams and expertise to connect and collaborate. Unlike WSS, SharePoint Server is not free and requires an additional license. MOSS 2007 comes in two versions – Standard and Enterprise.
The main components of SharePoint 2007 are

collaboration,
portals,
enterprise search,
enterprise content management,
business process and forms,
and business intelligence.

Previous versions of SharePoint Server included SharePoint Portal Server 2003 and before that SharePoint Portal Server 2001. To preview SharePoint’s new features visit the Microsoft Office SharePoint Server 2007 demo.

Windows SharePoint Services 3.0 :

Windows SharePoint Services 3.0 is the platform on which all SharePoint Products and Technologies are built. WSS 3.0 is for is suitable for small teams, projects and organizations.
WSS’s project collaboration, document workspace, meeting sub-site, and discussion board features allow individuals and small teams to collaborate and share information online. Past versions of Windows SharePoint Services included Windows SharePoint Services 2.0 and SharePoint Team Services. New features in WSS 3.0 include integrated workflows, RSS feeds, blogs, wikis and ASP-style Web parts. To preview more of WSS 3.0’s new features visit the Microsoft
Windows SharePoint Services 3.0 demo.
Not sure which SharePoint technology is right for you?
Visit Microsoft online to find out which SharePoint technology meets your company’s requirements.

Microsoft Office SharePoint Server 2007 Top 10 Benefits:

1. Provide a simple, familiar, and consistent user experience.

Office SharePoint Server 2007 is tightly integrated with familiar client desktop applications, e-mail, and Web browsers to provide a consistent user experience that simplifies how people interact with content, processes, and business data. This tight integration, coupled with robust out-of-the-box functionality, helps you employ services themselves and facilitates product adoption.

2. Boost employee productivity by simplifying everyday business activities.

Take advantage of out-of-the-box workflows for initiating, tracking, and reporting common business activities such as document review and approval, issue tracking, and signature collection. You can complete these activities without any coding. Tight integration with familiar client applications, e-mail, and Web browsers provide you with a simple, consistent experience. Modifying and extending these out-of-the-box workflow processes is made easy through tools like Microsoft Office SharePoint Designer 2007 (the next release of Microsoft Office FrontPage).

3. Help meet regulatory requirements through comprehensive control over content.

By specifying security settings, storage policies, auditing policies, and expiration actions for business records in accordance with compliance regulations, you can help ensure your sensitive business information can be controlled and managed effectively. And you can reduce litigation risk for your organization. Tight integration of Office SharePoint Server 2007 with familiar desktop applications means that policy settings are rendered onto client applications in the Microsoft Office system, making it simpler for employees to be aware of and comply with regulatory requirements.

4. Effectively manage and repurpose content to gain increased business value.

Business users and content authors can create and submit content for approval and scheduled deployment to intranet or Internet sites. Managing multilingual content is simplified through new document library templates that are specifically designed to maintain a relationship between the original version and different translations of a document.

5. Simplify organization-wide access to both structured and unstructured information across disparate systems.

Give your users access to business data found in common line-of-business systems like SAP and Siebel through Office SharePoint Server 2007. Users can also create personalized views and interactions with business systems through a browser by dragging configurable back-end connections. Enterprise-wide Managed Document Repositories help your organizations store and organize business documents in one central location.

6. Connect people with information and expertise.

Enterprise Search in Office SharePoint Server 2007 incorporates business data along with information about documents, people, and Web pages to produce comprehensive, relevant results. Features like duplicate collapsing, spelling correction, and alerts improve the relevance of the results, so you can easily find what you need.

7. Accelerate shared business processes across organizational boundaries.

Without coding any custom applications, you can use smart, electronic forms–driven solutions to collect critical business information from customers, partners, and suppliers through a Web browser. Built-in data validation rules help you gather accurate and consistent data that can be directly integrated into back-end systems to avoid redundancy and errors that result from manual data re-entry.

8. Share business data without divulging sensitive information.

Give your employees access to real-time, interactive Microsoft Office Excel spreadsheets from a Web browser through Excel Services running on Office SharePoint Server 2007. Use these spreadsheets to maintain and efficiently share one central and up-to-date version while helping to protect any proprietary information embedded in the documents (such as financial models).

9. Enable people to make better-informed decisions by presenting business-critical information in one central location.

Office SharePoint Server 2007 makes it easy to create live, interactive business intelligence (BI) portals that assemble and display business-critical information from disparate sources, using integrated BI capabilities such as dashboards, Web Parts, scorecards, key performance indicators (KPIs), and business data connectivity technologies. Centralized Report Center sites give users a single place for locating the latest reports, spreadsheets, or KPIs.

10. Provide a single, integrated platform to manage intranet, extranet, and Internet applications across the enterprise.

Office SharePoint Server 2007 is built on an open, scalable architecture, with support for Web services and interoperability standards including XML and Simple Object Access Protocol (SOAP). The server has rich, open application programming interfaces (APIs) and event handlers for lists and documents. These features provide integration with existing systems and the flexibility to incorporate new non-Microsoft IT investments.

Top 10 Benefits of Windows SharePoint Services:

1. Improve team productivity with easy-to-use collaborative tools
Connect people with the information and resources they need. Users can create team workspaces, coordinate calendars, organize documents, and receive important notifications and updates through communication features including announcements and alerts, as well as the new templates for creating blogs and wikis. While mobile, users can take advantage of convenient offline synchronization capabilities.


2. Easily manage documents and help ensure integrity of content
With enhanced document management capabilities including the option to activate required document checkout before editing, the ability to view revisions to documents and restore to previous versions, and the control to set document- and item-level security, Windows SharePoint Services can help ensure the integrity of documents stored on team sites.


3. Get users up to speed quickly
User interface improvements in Windows SharePoint Services 3.0 include enhanced views and menus that simplify navigation within and among SharePoint sites. Integration with familiar productivity tools, including programs in the Microsoft Office system, makes it easy for users to get up to speed quickly. For example, users can create workspaces, post and edit documents, and view and update calendars on SharePoint sites, all while working within Microsoft Office system files and programs.

4. Deploy solutions tailored to your business processes
While standard workspaces in Windows SharePoint Services are easy to implement, organizations seeking a more customized deployment can get started quickly with application templates for addressing specific business processes or sets of tasks.

5. Build a collaboration environment quickly and easily
Easy to manage and easy to scale, Windows SharePoint Services enables IT departments to deploy a collaborative environment with minimal administrative time and effort, from simple, single-server configurations to more robust enterprise configurations. Because deployment settings can be flexibly changed, less pre-planning time is required and companies can get started even faster.

6. Reduce the complexity of securing business information
Windows SharePoint Services provides IT with advanced administrative controls for increasing the security of information resources, while decreasing cost and complexity associated with site provisioning, site management, and support. Take advantage of better controls for site life-cycle management, site memberships and permissions, and storage limits.

7. Provide sophisticated controls for securing company resources
IT departments can now set permissions as deep down as the document or item level, and site managers, teams, and other work groups can initiate self-service collaborative workspaces and tasks within these preset parameters. New features enable IT to set top-down policies for better content recovery and users, groups, and team workspace site administration.

8. Take file sharing to a new level with robust storage capabilities
Windows SharePoint Services supplies workspaces with document storage and retrieval features, including check-in/check-out functionality, version history, custom metadata, and customizable views. New features in Windows SharePoint Services include enhanced recycle bin functionality for easier recovery of content and improved backup and restoration.

9. Easily scale your collaboration solution to meet business needs
Quickly and easily manage and configure Windows SharePoint Services using a Web browser or command-line utilities. Manage server farms, servers, and sites using the Microsoft .NET Framework, which enables a variety of custom and third-party administration solution offerings.

10. Provide a cost-effective foundation for building Web-based applications
Windows SharePoint Services exposes a common framework for document management and collaboration from which flexible and scalable Web applications and Internet sites, specific to the needs of the organization, can be built. Integration with Microsoft Office SharePoint Server 2007 expands these capabilities further to offer enterprise-wide functionality for records management, search, workflows, portals, personalized sites, and more.

Ref : http://www.sharepointhq.com/

How to use CASE statements in SQL Query : + SQL SERVER 2005

First lets create a sample table named testable

CREATE TABLE [dbo]. [testable]
(

[MaterialID] [int] NOT NULL,
[type] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Description] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[value] [decimal](18, 0) NULL

) ON [PRIMARY]

Now lets insert some values like

INSERT INTO testtable
SELECT 1,'cem','RAO',2
UNION ALL
SELECT 5,'wtr','Water',4
UNION ALL
SELECT 6,'cem','rao',5


Now write a query to that selects the column MaterialID, and two assigned columns named CementDescription and TestDescription where the CementDescription column should be filled with ‘CEMEMT’ for each row in the table where the type is ‘cem’ and the WaterDescription column should be filled with ‘Water’ for each row of the table where the type is ‘wtr’.

SELECT MaterialID,
CASE WHEN type = 'cem' THEN 'CEMENT' ELSE NULL END as CementDescription ,
CASE WHEN type = 'wtr' THEN 'WATER' ELSE NULL END as WaterDescription
FROM testtable


OUTPUT:

MaterialID CementDescription WaterDescription

1 CEMENT NULL
2 NULL WATER
3 CEMENT NULL


Not only this eg. there are lot to do with CASE in SQL.

Dec 23, 2008

Threads Implementation in C# + source code

Thread in C# :
Introduction to Threads In C# :
Threads: Threads are often called lightweight processes. However they are not process.es

A Thread is a small set of executable instructions, which can be used to isolate a task from a process.
Multiple threads are efficient way to obtain parallelism of hardware and give interactive user interaction to your applications.

C# Thread:.
. Net Framework has thread-associated classes in System.Threading namespace. The following steps demonstrate how to create a thread in C#.

Step 1. Create a System.Threading.Thread object.
Creating an object to System.Threading.Thread creates a managed thread in .Net environment. The Thread class has only one constructor, which takes a ThreadStart delegate as parameter. The ThreadStart delegate is wrap around the callback method, which will be called when we start the thread.


Step 2: Create the call back function
This method will be a starting point for our new thread. It may be an instance function of a class or a static function. Incase of instance function, we should create an object of the class, before we create the ThreadStart delegate. For static functions we can directly use the function name to instantiate the delegate. The callback function should have void as both return type and parameter. Because the ThreadStart delegate function is declared like this. (For more information on delegate see MSDN for “Delegates”).


Step 3: Starting the Thread.
We can start the newly created thread using the Thread’s Start method. This is an asynchronous method, which requests the operating system to start the current thread.
For Example:
// This is the Call back function for thread.

Public static void MyCallbackFunction()
{
while (true)
{
System.Console.WriteLine(“ Hey!, My Thread Function Running”); ………
}
}

public static void Main(String []args)
{
// Create an object for Thread
Thread MyThread = new Thread(new ThreadStart (MyCallbackFunction));
MyThread.Start() ……
}

Killing a Thread:
We can kill a thread by calling the Abort method of the thread. Calling the Abort method causes the current thread to exit by throwing the ThreadAbortException.

MyThread.Abort();

Suspend and Resuming Thread:

We can suspend the execution of a thread and once again start its execution from another thread using the Thread object’s Suspend and Resume methods.
MyThread.Suspend();

// causes suspend the Thread Execution.
MyThread.Resume() ;
// causes the suspended Thread to resume its execution.


Thread State:
A Thread can be in one the following state.
Unstarted - Thread is Created within the common language run time but not Started still.
Running - After a Thread calls Start method
WaitSleepJoin - After a Thread calls its wait or Sleep or Join method.
Suspended - Thread Responds to a Suspend method call.
Stopped - The Thread is Stopped, either normally or Aborted.

We can check the current state of a thread using the Thread’s ThreadState property.


Thread Priorty:
The Thread class’s ThreadPriority property is used to set the priority of the Thread.

A Thread may have one of the following values as its Priority:

Lowest

BelowNormal

Normal

AboveNormal

Highest.

The default property of a thread is Normal.

REF: Code project

How to select an item in a DropDownList by Value


1. //How to select an item in a DropDownList by Value

ListItem li = yourDropDownlist.Items.FindByValue(”yourValue”);

if (li != null)

yourDropDownlist.SelectedIndex = yourDropDownlist.Items.IndexOf(li);

2. //How to check if value exists in DropDownList

public static bool IsValueInDropdownList(DropDownList controlName,string strValue)

{

if (controlName.Items.FindByValue(strValue) != null)

return true;

else
return false;

}

How to Remove item from DropDownList by Value

// 1st method, to Remove item from DropDownList by Value
ListItem li = dropdownlist.Items.FindByValue(strValue);
if(li != null)
dropdownlist.Items.Remove(li);
// 2nd method, combined form
dropdownlist.Items.RemoveAt(
dropdownlist.Items.IndexOf(dropdownlist.Items.FindByValue(strValue))
);

Dec 22, 2008

CLR Stored Procedure to decrypt the encrypted value

Here is a CLR Stored Proc to decrypt the encrypted value and return it through output variable.

After launching Visual Studio 2005 choose File -> New Project.
In the dialog box under Project Type choose Visual C# -> Database and then choose SQL Server Project on the right side.
I named my project CLR_Decrypt . This creates a solution and a project both named CLR_Decrypt . Visual Studio will also ask you to create a database reference or use an existing one.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using Microsoft.SqlServer.Server;

public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void CLR_Decrypt(SqlString employeeID, out SqlBinary decryptedSignatureBytes)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Context Connection=true";
string signatureString = string.Empty;
string signatureString1 = string.Empty;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = @"SELECT EncryptedSignatureImage
FROM
[dbo].[LDI_EmployeeDigitalSignature]
WHERE
EncryptedEmployeeID = '" + employeeID.ToString() + "'";
conn.Open();

SqlDataReader rdr = cmd.ExecuteReader();
// This to call the Decrypt method to Decrypt the already encrypted text.
using (rdr)
{
while( rdr.Read() )
{
signatureString = rdr.GetString(0).ToString();
signatureString1 = DecryptText(signatureString);
}
}

// To convert string to SQL binary
decryptedSignatureBytes = Convert.FromBase64String(signatureString1);
rdr.Close();
conn.Close();
}

Dec 18, 2008

how to Export Grid view To Excel + Asp.Net 2.0 + C#

The below code Exports the Grid view to Excel in C#.

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;

///
/// Exports Grid To Excel
///

private void ExportToExcel(GridView gv)
{
StringWriter stw = null;
HtmlTextWriter htextw = null;
string fileName = string.Empty;

fileName = "Test";
try
{
HtmlForm form = new HtmlForm();
string attachment = "attachment; filename=" + fileName + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
Response.Buffer = true;
stw = new StringWriter();
htextw = new HtmlTextWriter(stw);
form.Controls.Add(gv);
this.Controls.Add(form);
form.RenderControl(htextw);
Response.Write(stw.ToString());
gv.Columns[10].Visible = true;
Response.End();
}
finally
{
stw = null;
htextw = null;
}
}


This code will open a open or Save dialog to open or save the .xls files created.

How to write a Property for ListBox to Generate ID List for Selected Items + C#

This is Property for ListBox to Generate ID List for Multiple Selected Items.
Use this namespace because here we use regex in the property.
using System.Text.RegularExpressions;

///
/// Gets Or Sets the IDsList.
///

private string IDsList
{
get
{
string IDs = string.Empty;
foreach (ListItem item in lbSample.Items)
{
if (item.Selected)
IDs = IDs + item.Value + ",";
}
IDs = System.Text.RegularExpressions.Regex.Replace(IDs, ",$", "");
return IDs;
}
set
{
foreach (int item in value)
{
if (lbSample.Items.FindByValue(item.ToString()) != null)
lbSample.Items.FindByValue(item.ToString()).Selected = true;
}
}
}

This will automatically return the list of IDs selected in the List box.

Oct 24, 2008

SQL SERVER 2005 SYNONYMS - Usage And Limitations


SYNONYMS:

Problem:

At work we face situations like ,

1. where tables created in the production database are required to move to another DB as a minimal time period, Moving the table with data's is a tedious job

2. And also we use various SPs, TVF Functions in some DB say DB1. When we are working in some other DB2 and we have situation to use the same SPs and Functions in DB1 for a test process, here we need to run the whole scripts in DB2 and we have to drop it if it is no more useful which comsume time

Solution:

The feature is SYNONYMs in SQL Server 2005. SYNONYMs is new to SQL Server 2005. It is a way to give an alias to an already existing or potential new object(May be a Table,SP,Functions,Views etc). It is just a pointer or reference, so it is not considered to be an object.

Required Permissions:

In order to create a synonym, you need to have CREATE SYNONYM permissions. If you are a sysadmin or db_owner you will have these privileges or you can grant this permission to other users. Also, you create a synonym that crosses databases you will need permissions for the other database as well..

CREATING SYNONYMs:

A SYNONYM can be created within a DB or Between DBs and also Between DBs in Different Servers.

Example 1:

Here is an Example for Creating a Synonyms within a DB

Syntax:

CREATE SYNONYM [SynName] FOR [ObjectName]

USE AdventureWorks

GO

CREATE SYNONYM MySyn FOR Production.Location

GO
To check that this works you can issue a query like

SELECT * FROM MySyn

This returns the values of the table Production.Location . This any modifications to this Synonyms will reflect in Production.Location table.

Say for example

UPDATE MySyn

SET Name = 'MukundsIdeas'

WHERE LocationID = 1

Executing this query will affect the values in the
Production.Location table of AdventureWorks DB.

Example 2:

Here is an example to create the SYNONYM in one database that references an object in another database.


USE master

GO

CREATE SYNONYM dbo.MySyn FOR AdventureWorks.Production.Location

GO

This creates a Synonym that can be accessible form any DB inside the Same Server.

Note: Make note on what Schema your DB use. For eg : if ur DB uses schema dbo then u should mention it as

CREATE SYNONYM dbo.MySyn FOR AdventureWorks.dbo.Production.Location

Example 3:

USE master
GO
CREATE SYNONYM dbo.MySyn FOR [UrServerName].[DBName].[TableName or SPname or Functionname or viewname etc]
GO

To get the meta data for all synonyms use the following command

SELECT * FROM sysobjects WHERE xtype = 'SN' ORDER BY NAME

And to drop the synonym use the following command

USE AdventureWorks;

GO

DROP SYNONYM MySyn

GO

SYNONYM's can be very useful and can be created for

1. Tables
2. Views
3. Assembly Stored Procedures,

4. Table Valued Functions,

5. Aggregations
6. SQL Scalar Functions
7. SQL Stored Procedures
8. SQL Table Valued Functions
9. SQL Inline-Table-Valued Functions
10. Local and Global Temporary Tables
11. Replication-filter-procedures
12. Extended Stored Procedures

Benefits :

SYNONYMs provide a layer of abstraction over the referenced object
Allow changes to complicated (multi part) and lengthy names with a simplified alias as a same server resident object.


Provides flexibility for changing the location of objects without changing existing code.


SYNONYMs can be created in the same database to provide backward compatibility for older applications in case of drop or rename of objects.


SYNONYMs can be useful if you give the front-end query tools like spreadsheets and Access linked tables direct links in to the tables.


Limitations:


SYNONYMs are loosely bound to the referenced objects. So you can delete a SYNONYM without getting any warning that it is being referenced by any other database object.


Chaining is not allowed. It means that you can not create SYNONYM of a SYNONYM.


Obviously consumes possible object names, as you can not create a table with the same name of a synonym


The object for which the SYNONYM is being created is checked at run time. It is not checked at creation time. So this means that if you make any related error e.g. spelling error, the synonym will created, but you will get an error while accessing the object.


SYNONYM can not be referenced in a DDL statement