Tuesday, September 29, 2009

Configure ASP.NET Membership Provider and Role Provider to Use own SQL Server Database

First create a data base using SQL Server. (You can use Visual Studio to create your database)

image

image

Type your new database name and press ok to continue. Then it will prompt dialog for creating a new database.

Then press ok , Now you created a database in your SQL Server.

After that go to Visual Studio Command prompt

Program Files—> Visual Studio 2008 command prompt

and type aspnet_regsql.exe 

or

C:\Windows\Microsoft.NET\Framework\v2.oxx and run Aspnet_regsql.exe.

This command will launch wizard which can use to generate relevant database structure to selected database.

image image
image image

Now we have to configure the web.config

<connectionStrings>
<
add name="ConnectionString"
connectionString="Data Source=TestDB;Initial Catalog=Login;User ID=sa;Password=sapassword"/>
</
connectionStrings>
 <system.web>
<
roleManager enabled="true" defaultProvider="SqlRoleProvider">
<
providers>
<
clear/>
<
add name="SqlRoleProvider"
connectionStringName="ConnectionString"
type="System.Web.Security.SqlRoleProvider"/>
</
providers>
</
roleManager>

<
membership defaultProvider="SqlProvider"
userIsOnlineTimeWindow="15">
<
providers>
<
clear />
<
add
name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="ConnectionString"
applicationName="MyApplication"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed" />
</
providers>
</
membership>
</
system.web>

There can be other tags in between System.web tag.

Friday, September 25, 2009

Change Crystal Report Page Size in Visual Studio

When you open a crystal report, Visual Studio giving a menu called CrystalReport. Go to that menu and go to print set up . now you can change the page size .

Sunday, September 20, 2009

Hide and Show Crystal Report’s Sub Report when we need

Refer to my previous post assume you want to display the sub report only data is available. therefore you can check the data for row availability and if rows are exists you can  display the report. In my example we are placed our sub report in section 4 in main report. thus we can use following code to display the sub report only data is available.

if (dts.Rows.Count > 0)
{
Ci.Subreports["SubBalance"].SetDataSource((DataTable)dts);
}
else
{
Ci.ReportDefinition.Sections[3].SectionFormat.EnableSuppress = true;
}

How to Create a Crystal Report Sub Report in C#.NET

First you need to create the main report.  (Read .. How to Create a Crystal Report using Data sets in C#.NET)

Then right click the area which you want to insert a sub report. In my example I’m going to create a sub report for displaying InvoiceNumber , Balance (refer to my previous post) .

image

Then place the report and design the sub report as we did in the main report. Finally right click the sub report and go to Format Object and Give the Object name as SubBalance.  also give the report name as SubBalance when the time of creating the report. Now your main report looks like ..

image

Now you need to load data to the sub report as well as main report when we press the select button using data adapters. (refer Previous post )

private void btnView_Click(object sender, EventArgs e)
{
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
cb.UserID = "sa";
cb.Password = "sa123";
cb.InitialCatalog = "CustomerInfo";

// Create SQL Connection
SqlConnection sc = new SqlConnection(cb.ConnectionString);

CusDataSetTableAdapters.CusMainTableAdapter Ta =
new
CusDataSetTableAdapters.CusMainTableAdapter();
Ta.Connection = sc;
CusDataSet.CusMainDataTable Td = Ta.GetDataByName(txtCusName.Text);

// Create the mainReport
CustomerInfo Ci = new CustomerInfo();
Ci.SetDataSource((DataTable)Td);

// Load data to the sub report
CusDataSetTableAdapters.CusBalanceTableAdapter Tas =
new
CusDataSetTableAdapters.CusBalanceTableAdapter();
Tas.Connection = cn;
CusDataSet.CusBalanceDataTable dts =
Tas.GetBalanceByCusName(txtCusName.Text);
Ci.Subreports["SubBalance"].SetDataSource((DataTable)dts);

crystalReportViewer1.ReportSource = Ci;

}

(Read .. Hide and Show Crystal Report’s Sub Report when we need)

How to Create a Crystal Report using Data sets in C#.NET

Assume that you already SQL server database created and table also. Following illustrate our table structure and data.

CustomerName InvoiceNum TotalAmount Paid Balance
Amal 10001S 1000.00 900.00 100.00
Amal 10002S 2500.00 2000.00 500.00
Amal 10003S 1800.00 1500.00 300.00
Amal 10004S 2500.00 2000.00 500.00
Nimal 10005S 3000.00 3000.00 0.00
Nimal 10006S 1000.00 1000.00 0.00
Nimal 10007S 1500.00 1500.00 0.00

First you need to have a data connection created. (Read ..How to create a Data Connection to SQL Server using C#.net Wizard) 

Then you need to have a Data set created. (Read .. How to Create a DataSet, DataTables, Table Adapter Using C#.NET Wizard)  In here I’m going to create a report with main data by customer name (CustomerName, InvoiceNum , TotalAmount) therefore i need a data table with relevant fields.

To add a Crystal Report go to Project –> Add new items –> Reporting –> CrystalReport.  Than give a name. In my example i gave a name as CustomerInfo.

image

Then above window will appear. In that select As a Black report and press next to proceed.  Then report design page will appear. First of all we need to set data sources relevant to  the report. Therefore i right click the database Field and go to Data Base Expert .. section.

image  

In Database Expert window find the relevant data set under the Project data. And select the data table listed and add it to the report as follows.

image

Then finally drag and  drop relevant fields from database field  to details section and create your report and save it. If you want you can also give report headers , page numbers and etc.. by right click and inset text object.  

image

Now we are going to Load the report to our form using CrystalReport viewer. When the user enter the customer name and press select our report will be displayed.

image

private void btnView_Click(object sender, EventArgs e)
{
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
cb.UserID = "sa";
cb.Password = "sa123";
cb.InitialCatalog = "CustomerInfo";

// Create SQL Connection
SqlConnection sc = new SqlConnection(cb.ConnectionString);

CusDataSetTableAdapters.CusMainTableAdapter Ta =
new
CusDataSetTableAdapters.CusMainTableAdapter();
Ta.Connection = sc;
CusDataSet.CusMainDataTable Td = Ta.GetDataByName(txtCusName.Text);

// Create a Report
CustomerInfo Ci = new CustomerInfo();
Ci.SetDataSource((DataTable)Td);

crystalReportViewer1.ReportSource = Ci;

}

(Read… How to Create a Crystal Report Sub Report in C#.NET)

Select Record using Data Grid,Dataset and Table Adapters in C#.Net

First of all you need to have a Data Connection. (Read.. How to create a Data Connection to SQL Server using C#.net Wizard )

Then you need to have data set and table adapters configured (Read.. How to Create a Dataset, Data Tables, Table Adapter Using C#.NET Wizard) 

Then add a data grid (dtgrid) to your windows form.  And use following code. When we not saved our connection we need to give connection settings to the table adapter when ever it wants to connect to the data base.

image

private void btnSelect_Click(object sender, EventArgs e)
{
// using System.Data.SqlClient; import this namespace
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
cb.UserID = "sa";
cb.Password = "sa123";
cb.InitialCatalog = "CustomerInfo";

// Create SQL Connection by giving SQL Connection String
SqlConnection sc = new SqlConnection(cb.ConnectionString);

CusDataSetTableAdapters.CusMainTableAdapter Ta =
new
CusDataSetTableAdapters.CusMainTableAdapter();
Ta.Connection = sc;
CusDataSet.CusMainDataTable Td = Ta.GetDataByName(txtCutName.Text);

dtGrid.DataSource = Td;
}

How to Create a DataSet, DataTables, Table Adapter Using C#.NET Wizard

To create a DataSet First you need to add a data connection to visual studio (Read…). 

Assume we are having a table called CusTransactions and having columns CustomerName , InvoiceNum, TotalAmount , Paid , Balance.

In my scenario I want to add a Data table to my data set including CustomerName , InvoiceNum and TotalAmount. therefore  first we want to add a dataset. Thus go to Project –> Add new item –> DataSet. And named it as CusDataSet.

When you add the data set visual studio shows DataSet Designer. This is the space you can configure your data adapters  and  data tables. ( To add data adapters you can straightway drag and drop tables from your data connection also.)

To add a data adapter right click the dataset  designer window and goto Add—> TableAdapter. Then the coming window select the relevant data connection. (You can also create new data connection here)  

 image 

After the selecting the connection click next to proceed.  Then you select Use SQL Statement because we are going to create SQL statements in the next screen.

  image

Though our table had five columns I’m using this table adapter to select three columns CustomerName , InvoiceNum , TotalAmont by CustomerName. To generate the SQL you can use Query Builder or just type what you want. Use @symbol to give a parameter to the query or in the QueryBulder in Filter Field type @Cusname.  Using this Data adapter we can also insert and delete . But all methods should match data table schema . Means In here we are selecting customerName, InvoiceNum, TotalAmount thus all creating method contains only those three columns. In the Advanced Options Button you can decide whether   you want Insert or Delete methods.

image

In here you can select what are the methods you want. And click finish. As we did previous add another table adapter for same table allowing to select InvoiceNumber and Balance by Customer name . Finally you can save your dataset by closing it or using save button. Then you can see the data set in designer as follows.

image

To rename the table adapters you can right click the adapter and rename it.

Read.. (Select Record using Data Grid,Dataset and Table Adapters in C#.Net)

Saturday, September 19, 2009

How to create a Data Connection to SQL Server using C#.net Wizard

For this first  go to server explorer and right click it. then go to Add connection. Then a screen will  come. In that you can enter the server name  and login credentials (username password or windows authentication). Then select the relevant database and use Test Connection to verify the connection. (Windows Authentication takes your windows credentials to log in to SQL Server, If you cant find the Server name open the SQL Server Management Studio and go to server properties.)

image

Read.. (How to Create a DataSet, DataTables, Table Adapter Using C#.NET Wizard)

Friday, September 18, 2009

Microsoft Expression Encoder 3

image

Encode a wide array of video file formats, stream live from webcams and camcorders or screen capture your PC. Make simple edits to video files and enhance your media with overlays and advertising. Choose encoding settings, choose from a range of player templates and publish rich media experiences with Microsoft Silverlight.

Read more…

It’s amazing , Microsoft Expression Web 3

Deliver visually compelling, standards-compliant Web experiences with Expression Web 3

Whether you're an expert or just getting started, building standards-based Web sites is faster and easier with Microsoft Expression Web 3.

      Top Features

  • Professional Code Editor
  • Professional Design Surface
  • Visual Diagnostics
  • Broad support for Industry-Standard Technologies
  • Broad support for Industry-Standard Technologies

       and many more….

image

image

It’s cool, Microsoft Expression Design 3

image

Microsoft Expression Design 3 creates graphics for use in your design projects.

Microsoft Expression Design 3 is the perfect companion to Expression Blend or Expression Web. Leverage existing artwork, or use intuitive drawing tools to quickly build sophisticated vector assets. Seamlessly transfer them to your Expression Blend or Expression Web projects knowing that their fidelity will be maintained throughout the entire designer-developer workflow.

Top Features

  • Create Graphics
  • Powerful Tools
  • Editable Effects

Read More

image

Tuesday, September 15, 2009

Blog Writing Software

I have tried many blog writers but ultimately Windows Live Writer suits my preference.  its very amazing product with marvelous features.

image

This includes

  • WYSIWYG Editing
  • Photo Editing
  • Plugging Support
  • all most all blog platforms

Monday, September 14, 2009

Querying XML using LINQ to XML in C#

<Customers>
<Customer id="1" orderdate="4/1/1968">Paul Koch</Customer>
<Customer id="2" orderdate="7/5/1988">Bob Kelly</Customer>
<Customer id="3" orderdate="3/24/1990">Joe Healy</Customer>
</Customers>
Assume this is the XML file you want to search and it is stores in C:\ drive.
 XDocument myDoc = XDocument.Load(@"C:\sample.xml");
Ex –1 get the customer who’s having id 2
Method 1
you can use var type variable and through iteration you can get the result. this method is good when you have more than one record.
 var q = from c in myDoc.Descendants("Customer")
 where (int)c.Attribute("id") == 2
 select c;
Receiving values by iterating through foreach loop. 
 foreach (XElement item in q)
 {
 String id =item.Attribute("id").Value;
 String orderdt = item.Attribute("orderdate").Value;
 String name = item.Value;
}
Method 2
if you know it is a single value (assume id is unique for customers)
 XElement x = myDoc.Descendants("Customer").Single(c => 
 Convert.ToInt32(c.Attribute("id").Value) ==2);
 String id = x.Attribute("id").Value;
 String orderdt = x.Attribute("orderdate").Value;
 String name = x.Value;

Thursday, September 10, 2009

Creating and saving XML using LINQ to XML in C#

XML generation is much easier now in C#. You can use System.Xml.Linq namespace to create XML content much faster and easy.
lets look at the following XML.
<Customers>
<Customer id="1" orderdate="4/1/1968">Paul Koch</Customer>
<Customer id="2" orderdate="7/5/1988">Bob Kelly</Customer>
<Customer id="3" orderdate="3/24/1990">Joe Healy</Customer>
</Customers>

Create XML using Linq to XML
Following describes how to create the above xml using xElements.
XElement xml = new XElement("Customers");
XElement Customer = new XElement("Customer");
Customer.Add(new XAttribute("id",1));
Customer.Add(new XAttribute("orderdate", "4/1/1968"));
Customer.Value = "Paul Koch";
xml.Add(Customer);
Customer = new XElement("Customer");
Customer.Add(new XAttribute("id", 2));
Customer.Add(new XAttribute("orderdate", "7/5/1988"));
Customer.Value = "Bob Kelly";
xml.Add(Customer);
Customer = new XElement("Customer");
Customer.Add(new XAttribute("id", 3));
Customer.Add(new XAttribute("orderdate", "3/24/1990"));
Customer.Value = "Joe Healy";
xml.Add(Customer);
you can get the xml string by using xml.ToString()

Save  XML File using Linq to XML
in generally there should be a xml declaration when we are saving the file. as an example
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
So create a file like that add following code to bottom of the above code.

XDocument Xdoc = new XDocument();
XDeclaration Xdec = new XDeclaration("1.0", "utf-8", "yes");
Xdoc.Declaration = Xdec;
Xdoc.Add(xml);
Xdoc.Save(@"C:\sample.xml");

Change APN Setting programmatically in Blackberry

As shown bellow you want to set APN and Username (optional),Password (optional) in your connection programmatically, if you are not set it in the device. This also caused to Tunnel Failed error.

public String HttpGET(String Url)
 {
  String AppendURL = ";deviceside=true ;apn=internet.com";
  AppendURL +=";tunnelauthusername=user165;tunnelauthpassword=user165password";  
  try {
   HttpConnection httpConnection = (HttpConnection) Connector.open(Url+AppendURL);
   httpConnection.setRequestMethod(HttpConnection.GET);
   InputStream inputStream = httpConnection.openInputStream();
        
   StringBuffer sb = new StringBuffer();
   int C;
        
   while( -1 != (C = inputStream.read())) 
   { sb.append((char)C); }
 
   return sb.toString();
   }
   catch (Exception e)
   { return "";      }
 } 

Change the MDI child form’s background color when MDI parent clicks

When you create a form as a MDI child , sometimes you want to access the form object to do some modification from MDI parent. Using following mechanism you can change any associate property of the form.

here is a example of changing MDI child’s form background color when MDI parent menu clicks.

private void MDIToolStripMenuItem_Click(object sender, EventArgs e)
{
    Control[] CC = this.Controls.Find("Form1",true);
    foreach (var item in CC)
    {
        if (item.GetType().Name=="Form1" )
        {
            Form1 F = (Form1)item;
            F.BackColor = Color.Aqua;
        }
    }
}

Wednesday, September 9, 2009

How to add Button,Checkbox, Radio Button ,any Control to Context Menu in C#

image

Context Menu is a menu that pops when we click on a control. We can add any windows controls to this context menu using ToolStripControlHost .

There are mainly two ways of doing that. we can either extend the ToolStripControlHost to our class or give the control as a constructor.

Following describe the second method. Say if you have a button called MainButton and context menu should come  when we click that button. and drag and drop contextMenuStrip from the toolbox.

private void MainButton_Click(object sender, EventArgs e)
{
// Adding a button to Menu
Button B = new Button();
B.Text = "My Button";

// This will bind the event for the button
B.Click += new EventHandler(B_Click);
ToolStripControlHost Ch = new ToolStripControlHost(B);

// Adding a Month Calender
MonthCalendar Mc = new MonthCalendar();
ToolStripControlHost Ch1 = new ToolStripControlHost(Mc);

//Adding a TextBox
TextBox Tb = new TextBox();
Tb.Text = "Add Text";
ToolStripControlHost Ch2 = new ToolStripControlHost(Tb);

//Adding a Check Box
CheckBox Cb = new CheckBox();
Cb.Text = "My Check Box";
ToolStripControlHost Ch3 = new ToolStripControlHost(Cb);

//Adding a Radio Buttion
RadioButton Rb = new RadioButton();
Rb.Text = "My Radio Button";
ToolStripControlHost Ch4 = new ToolStripControlHost(Rb);

contextMenuStrip1.Items.Clear();
contextMenuStrip1.Items.Add(Ch);
contextMenuStrip1.Items.Add(Ch1);
contextMenuStrip1.Items.Add(Ch2);
contextMenuStrip1.Items.Add(Ch3);
contextMenuStrip1.Items.Add(Ch4);

contextMenuStrip1.Show(MainButton, 40, 10);
}
void B_Click(object sender, EventArgs e)
{
MessageBox.Show("Clicked");
}

Tuesday, September 8, 2009

How to change the windows form shape in C#

you can change the windows form shape what ever you want. Cool ah.. 

image

Lets try to do this.

  • Add new form to your project. (set FormBorderStyle  to None)

image

  • Use following code for form load
private void Form1_Load(object sender, EventArgs e)
{
GraphicsPath g = new GraphicsPath();
//using System.Drawing.Drawing2D;
g.AddEllipse(0, 0, 200, 200);

Region r = new Region(g);
this.Region = r;
}

Thursday, September 3, 2009

How to do implement override in C#

image
class SuperClass
{
    public virtual void MyMethod() 
    { // Code Here }
}
 
class SubClassA : SuperClass
{
    public override void MyMethod()
    { // Code Here }
}
 
class SubClassB : SubClassA
{
    public override void MyMethod()
    { // Code Here }
}

Override is method of implementing polymorphism. Though three classes have same method they will show a unique behavior. as an example,


SuperClass A = new SuperClass();
A.MyMethod();
// This will execute code defined in SuperClass

A = new SubClassA();
A.MyMethod();
// This will execute code defined in SubClassA

Read More

Retrieving Data from SQLServer using Data Set in C#

  • Assume that you have

    • SQLServer named as “My-PC
    • Database Named as “TestDB
    • UserID for SQL server as “Melick
    • Password for SQL server as “PassMelick”
String ConStr="";
ConStr="Data Source=My-PC;Initial Catalog=TestDB;Persist Security Info=True;"+
"User ID=Melick;Password=PassMelick";
SqlConnection sc = new SqlConnection(ConStr);
 
SqlCommand scmd = new SqlCommand();
scmd.CommandText = "SELECT * From Table1";
scmd.CommandType = CommandType.Text;
scmd.Connection = sc;
 
DataSet ds =new DataSet();
SqlDataAdapter da = new SqlDataAdapter(scmd);
da.Fill(ds);
 
string Name="";
int Age=0;
 
foreach (DataRow dtrow in ds.Tables["Table1"].Rows)
{
Name=dtrow["Name"].ToString();
Age=(int)dtrow["Age"];
} 

In here manually writing a connection string is difficult. therefore I always prefer to use SqlConnectionStringBuilder Class to generate the Connection String.


SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
sb.UserID = "Melick";
sb.Password = "PassMelick";
sb.InitialCatalog = "TestDB";
sb.DataSource = "My-PC";
 
SqlConnection sc = new SqlConnection(sb.ConnectionString);
 
SqlCommand scmd = new SqlCommand();
scmd.CommandText = "SELECT * From Table1;SELECT * From Table1";
scmd.CommandType = CommandType.Text;
scmd.Connection = sc;
 
DataSet ds =new DataSet();
SqlDataAdapter da = new SqlDataAdapter(scmd);
da.Fill(ds);
 
string Name = "";
int Age = 0;
 
foreach (DataRow dtrow in ds.Tables["Table1"].Rows)
{
// Table Having two columns Name and Age
Name =dtrow["Name"].ToString();
Age = (int)dtrow["Age"];
}

How to save server certificate to blackberry key store

  • First you have to download the certificate file manually. To do this open your Firefox browser and type the URL which enables SSL. Then you can see a Padlock bottom of the browser.
image
  • Double click the pad clock. then you can see the certificate window. Click View Certificate button. In the certificate viewer window select Details Tab and select Export button.
image image
  • Then Save your Certificate as X.509 (PEM) format.  You will get this kind of file.
image
  • Open eclipse and Create new Blackberry Project. Copy Certificate file in to the same package that class created. (In here I'm writing my code in Main.java class thus i copied the certificate file in to Main package.)image
  • Following shows code sample
public Certificate ReadFile()
{   
try {
Class classs = Class.forName("com.ironone.main.Main");
InputStream is = classs.getResourceAsStream("/DigiCertEVRootCA.crt");
// Certificate File Name :DigiCertEVRootCA.crt
byte[] data = new byte[is.available()];
is.read(data, 0, is.available());
Certificate c =CertificateUtilities.readCertificateFile(null, data);
// Import net.rim.device.api.crypto.certificate.CertificateUtilities
return c;    
}
catch (Exception ioe) {
return null;    
}        
}
public void addCertToDeviceKeyStore (Certificate certificate)
{
KeyStore keyStore = DeviceKeyStore.getInstance();
//check if certificate is not already in the DeviceKeyStore
if (!keyStore.isMember(certificate))
{
try{
String SFN = certificate.getSubjectFriendlyName();
CertificateStatus CS=certificate.getStatus();
keyStore.set(null,SFN ,certificate,CS , keyStore.getTicket());
}
catch (Exception e)
{ } 
}
}
public static void main(String args[])
{ 
Main TheMain = new Main();
TheMain.enterEventDispatcher();
}
public Main()
{
addCertToDeviceKeyStore(ReadFile());
}