Thursday, January 12, 2012

Exporting long strings to Excel format using Active Reports.

When you are pulling a huge text field data from the database, Active Reports breaks the text into multiple rows. Sorting the excel sheet columns will be a problem with the way active report generates the Exel report. Below is the code to change the default behavior of the excel format Active Report. All you will need to do is explicitly set wordwrap on the controls to false. Here, I am looping to find all the controls and setting the word wrap on each control to false.

// To fix excel reports from displaying single cell data in multiple rows
if (IsXls == true)
{
Section Hsec = this.Sections["pageHeader"];
for (int i = 0; i < Hsec.Controls.Count; i++)
{
if ((Hsec.Controls[i].GetType()).ToString() == "DataDynamics.ActiveReports.Label")
{
((Label)(Hsec.Controls[i])).WordWrap = false;
}
}

Section sec = this.Sections["detail"];
for (int i = 0; i < sec.Controls.Count; i++)
{
if ((sec.Controls[i].GetType()).ToString() == "DataDynamics.ActiveReports.TextBox")
{
((TextBox)(sec.Controls[i])).WordWrap = false;
}
}
}

Tuesday, January 10, 2012

Java vs CSharp

I started reading a book on Java - 'Java How to Program' to learn and possibly start working with it. As I read, it is so similar to C#. There are just a very few subtle differences.

Static Import: A static import declaration in java enables you to import the static members of a class or interface so you can access them via their unqualified names in your class. The class name and a dot (.) are not required to use an imported static member.

Syntax:
import static packageName.ClassName.staticMemberName; to import a particular static member.
import static packageName.ClassName.*; to import all static members of the specified class

Example:
// Static import of Math class methods.
public class StaticImportTest
{
public static void main( String[] args )
{
System.out.printf( "sqrt( 900.0 ) = %.1f\n", );
System.out.printf( "ceil( -9.8 ) = %.1f\n", );
System.out.printf( "E = %f\n", E );
System.out.printf( "PI = %f\n", PI );
} // end main
}

Final Modifier: Final Modifier in Java is same as readonly in C#. final modifier in Java and readonly modifier in C# can be initialized when they're declared. If they are not, they must be initialized in every constructor of the class. Initializing constants in constructors enables each object of the class to have a different value for constant.

package: package in java is same as namespace in C#.

Import: Import in Java is same as Using in C#.
Java source code file has the following order
1. a package declaration (if any)
2. import declarations (if any), then
3. class declarations
Only one of the class declarations in a particular file can be public.

C# source code file has the following order
1. using declarations (if any)
2. namespace declaration (if any)
3. class declarations
Any number of class declarations in a particular file can be public.

Access modifiers :In Java, if no access modifier (public, protected or private) is specified for a method or variable when it’s declared in a class, the method or variable is considered to have package access. If a class has no access modifier, then it can only be accessed from same package.
In C#, if no access modifier is specified, the default accessibility of class members (including methods) is private. If no access modifier is specified for a class, The default accessibility of a class itself is internal.

Super: To call a base class method in Java, Super followed by dot is used. In C# base followed by dot is used.

Extends:In java to extend from a base class, keyword 'extends' is used. In C# : is used.
Java example:
public class CommissionEmployee extends Object
{
...
}
@Override: To override a super class method in Java, '@Override' is used.
In C# 'override' is used.

Also in .Net, The overridden base method/property must be virtual, abstract, or override. Both the override method/property and the overridden method/property must have the same access level modifier. When a class contains an abstract method, that class must be declared as abstract. classes that derive from that abstract class, must provide an implementation for this abstract method. A class can have a virtual method. When you inherit from a class that has a virtual method, you can override the virtual method and provide additional logic, or replace the logic with your own implementation.

Java example:
@Override // indicates that this method overrides a superclass method
public String toString()
{
...
} // end

Class Object:All classes in Java inherit directly or indirectly from the Object class (package java.lang), so its 11 methods (some are overloaded) are inherited by all other classes - clone, equals, finalize, getClass, hashCode, wait, notify, notifyAll, toString.

Inheritence: In C#, To call a base class constructor from the derived class constructor, you should use ": base class name ( args)"
Csharp Example:
public abstract class supertest
{
private int x;
public supertest(int x)
{
this.x = x;
}
}
public class test : supertest
{
public test(int x): base(x){ }
}

In Java, you simply write super(args...); as the first line in the child class constructor to call the base class constructor
Java Example:
public abstract class supertest
{
private int x;
public supertest(int x)
{
this.x = x;
}
}
public class test extends supertest
{
public test(int x) { super(x); }
}

instanceof: Java's "instanceof" keyword equivalent in csharp is "is"
Java example:
if ( currentEmployee instanceof BasePlusCommissionEmployee )
{
}

C# example:
if ( currentEmployee is BasePlusCommissionEmployee )
{
}

Inteface: Interface in C# cannot contain fields.
In Java, Interface can contain fields and are implicitly public, static and final. All methods declared in an interface are implicitly public abstract methods. Interface methods in java are always public abstract, so they do not need to be declared as such. You will not have any compile errors by declaring methods in the interface public abstract.
In C#, you will have compile errors if you declare methods with any modifiers.

Implementing an interface: To implement an interface in java implements keyword is used. In C# ":" is used.
In Java, When a class implements from an interface, the class should override the methods defined in the interface using the keyword @override.
In C#, you do not override the method in the class implementing the interface.
Java example:
public interface Payable
{
double getPaymentAmount(); // You can declare public abstract double getPaymentAmount()
}
public class Invoice implements Payable
{
@Override
public double getPaymentAmount()
{
return getQuantity() * getPricePerItem(); // calculate total cost
} //
}

C# example:
public interface supertest
{
void printhello(string str); // You will have compile errors if you use public abstract void printhello(string str)
}
public class test : supertest
{
public void printhello(string str)
{
Console.WriteLine("hello Dear " + str);
}
}

In Java, when a class implements an interface, it makes a contract with the compiler stating either that the class will implement each of the methods in the interface or that the class will be declared abstract. So if you declare the class abstract, you do not have to implement the methods in the interface.
In C#, if the derived class does not implement the methods in the interface, you will have compile errors. If you want to declare the class that implements the interface abstract, you would have to still declare the methods you do not want to implement abstract inside the class.

Exception Handling: In Java exceptions are two types: 1. checked 2. unchecked. Java compiler enforces a catch-or-declare requirement for checked exceptions. All exception types that are direct or indirect subclasses of class RuntimeException (package java.lang) are unchecked exceptions. These are typically caused by defects in your program’s code. All classes that inherit from class Exception but not class RuntimeException are considered to be checked exceptions. Such exceptions are typically caused by conditions that are not under the control of the program— for example, in file processing, the program can’t open a file because the file does not exist. Classes that inherit from class Error are considered to be unchecked.
Another feature Java provides is Preconditions and Postconditions - A precondition must be true when a method is invoked. A postcondition is true after the method successfully returns. Typically, a method’s preconditions and postconditions are described as part of its specification. When designing your own methods, you should state the preconditions and
postconditions in a comment before the method declaration.

To catch multiple exceptions in java, operation '|' is used. The code is simple.
Java Example:
catch ( Type1 | Type2 | Type3 e )

A little more code should be written in C# to do the same.
C# Example:
catch (Exception ex)
{
if (ex is FormatException ||
ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
else
{
throw;
}
}


(To be Continued...)

Wednesday, December 21, 2011

How to call Server Side function from Client Side Code

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds.
1. Use __doPostBack() and IPostBackEventHandler.
2. Set hidden variables and sumbit the form using form.submit()
3. Use PageMethods in ASP.net AJAX.

PageMethods can possibly save you a large amount of bandwidth which can mean faster response times for visitors on slower connections. Instead of posting all of the form values, we can send only what is needed. Instead of returning a large chunk of data, we can return precisely what we need to display to the user. For performance and bandwidth sensitive situations, they may be the right tool. So use PageMethods where possible instead of UpdatePanel as UpdatePanel posts all of the page's form values when all you might need to pass to the server is very little information. Using PageMethods you can save bandwidth.

Here is a link to learn how to use PageMethods: http://www.dotnetcurry.com/ShowArticle.aspx?ID=109

Tuesday, December 20, 2011

Disable a button during postback

You may want to disable a button during postback to stop user from clicking the button before the results are returned. You could do this on the client side using the OnClientClick attribute. The problem with disabling a submit button on the client side is that it will cancel the browser's submit, and thus the postback. Hence your server side event (BtnSumbit_Click) will not trigger.

asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
OnClick="BtnSubmit_Click"
Text="Submit Me!"

The trick is to set the UseSubmitBehavior property to false. This tells .Net to inject the necessary client script to fire the postback anyway, instead of relying on the browser's form submission behavior.

asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
UseSubmitBehavior="false"
OnClick="BtnSubmit_Click"
Text="Submit Me!"

This property will inject __doPostBack giving us this rendered HTML:

input type="button" name="BtnSubmit"
onclick="this.disabled = true; this.value = 'Submitting...';__doPostBack('BtnSubmit','')"

Friday, July 1, 2011

How to determine the row size of all tables

A quick google brought me the below SQL and I been using this sql a lot.

SELECT OBJECT_NAME (sc.[id]) tablename
, COUNT (1) nr_columns
, SUM (sc.length) maxrowlength
FROM syscolumns sc
join sysobjects so
on sc.[id] = so.[id]
WHERE so.xtype = 'U'
GROUP BY OBJECT_NAME (sc.[id])
ORDER BY SUM (sc.length) desc

Wednesday, May 11, 2011

Comparing two database tables for equality

Binary_Checksum can be used to compare two tables for equality.
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) from dbo.[Table1]
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) from dbo.[Table2]

But there are some concerns about the algorithm that it might not always be unique

Example:

select binary_checksum('A') ,binary_checksum('AAAAAAAAAAAAAAAAA')

The out put is 65 and 65

select binary_checksum('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA A') ,binary_checksum('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAA')

The out put is 577 and 577.

So the other way to compare two tables cell by cell would be to write a query like this


SELECT COUNT(*) as cnt, MIN(ViewName) as TableName, col1, col2, ...
FROM
(
SELECT '[DataBase1].dbo.[TableName or ViewName goes here]' as ViewName,
*
FROM [DataBase1].dbo.[TableName or ViewName goes here] A
UNION ALL
SELECT '[DataBase2].dbo.[TableName or ViewName goes here]' as ViewName,
*
FROM [DataBase2].dbo.[TableName or ViewName goes here] B
) tmp
GROUP BY ALL col1, col2, ...
HAVING COUNT(*)%2 <> 0


UNION concatenates two tables
GROUP BY groups the records by comparing cell to cell of all the columns listed and merges all the matching rows as a single row with COUNT(*) displaying the number of matching rows that have been merged.

If there is a row in View1/Table1 that matches the row in View2/Table2, then COUNT returns an even number (after the entire cell by cell comparison is performed by group by).

If there are any rows in View1/Table1 and View2/Table2 that do match each other, then after the merge performed by GROUP BY, COUNT(*) returns an odd number.

COUNT(*) is an even number when all the data cells in view1 match to view2 and when divided by 2 the reminder is 0. If any rows do not match exactly cell by cell, COUNT(*) is an odd number and when divided by 2 has a reminder.

Hence

HAVING COUNT(*)%2 <> 0
Returns all the mismatched rows. The query does not return any results if View1 and View2 match.

To get the list of columns if you are comparing views run this script:

DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ', ', '') + c.name FROM sys.columns c, sys.views v
WHERE c.object_id = v.object_id
AND v.name = 'View Name here'
Print @Names










The out put is 577 and 577.

Tuesday, May 10, 2011

Caching using SqlCacheDependency class with command notification

Caching is very simple when caching a table

SqlCacheDependency dep = new SqlCacheDependency("Connection String", "dbo.tablename")

but when caching a sql command I had to struggle and it just did not work until I read this article and changed my query to not have any of these mentioned in the below article. The reason to cache a sql command instead of table was that I had to join more than two tables.

The reasons why cache was not working for me was I was doing two things that I am not supposed to do for the notifications to work.

1. My table names did not have two-part names like in dbo.tablename
It also means that all tables referenced in the statement must be in the same database.

2. I was using 'DISTINCT'. One of the many keywords Query notification does not support.

For full list of requirements for the Query notification to work, read the following article.

http://msdn.microsoft.com/en-us/library/aewzkxxh%28VS.80%29.aspx

Same rules apply if you want to Cache data from a stored procedure. The reason I like to use SqlCacheDependency class is because it uses the notification mechanism instead of polling.

object o = HttpContext.Current.Cache["MITES"];
if (o == null)
{
using (SqlConnection conn = new SqlConnection(GetConnectionString.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand ("GetMites",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
dtMites = new DataTable("dtMites");
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
SqlCacheDependency dep = new SqlCacheDependency(cmd);
da.Fill(dtMites);

// This is just test code to make sure cache is really working
/* DataRow row = dtMites.NewRow();
row[0] = "Retreived from database";
dtMites.Rows.Add(row);
*/
// The data returned has duplicates. dtMites.DefaultView.ToTable(true, "Table1")
// retrieves distinct rows from the datatable
HttpContext.Current.Cache.Add("MITES", dtMites.DefaultView.ToTable(true, "Table1"), dep,
Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1),
CacheItemPriority.Default, null);
return (DataTable)HttpContext.Current.Cache["MITES"];
}
}
}
}
else
{
// This is just test code to make sure cache is really working
/* dtMites = (DataTable)o;
DataRow row = dtMites.NewRow();
row[0] = "Retreived from Cache";
dtMites.Rows.Add(row);
return dtMites;
*/
return (DataTable)o;
}

You need to add some tags to the web.config file for this to work

<system.web>
<caching>
<sqlcachedependency enabled = "true" pollTime = "60000" >
<databases>
<add name="Connection String"
connectionStringName="Connection String"
pollTime="9000000"
/>
</databases>
</sqlCacheDependency>
</caching>


You will also need to add this to Application_Start method in Global.asax.cs file

protected void Application_Start(object sender, EventArgs e)
{
System.Data.SqlClient.SqlDependency.Start(System.Configuration.ConfigurationManager.ConnectionStrings["Connection String"].ConnectionString);
// Code that runs on application startup
}

on the database server run this command
Aspnet_regsql -S ServerName -U username -P Password -d DatabaseName -ed

Using Sql management studio run this script on the database

Run the script

DECLARE @SQL nvarchar(max)
BEGIN TRY
SET @SQL = 'ALTER DATABASE' + DatBaseName + 'SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE '
PRINT @SQL
EXEC sp_executesql @SQL
END TRY
BEGIN CATCH
SET @SQL = 'ALTER DATABASE' + DatBaseName + 'SET NEW_BROKER WITH ROLLBACK IMMEDIATE '
PRINT @SQL
EXEC sp_executesql @SQL
END CATCH
GO


If the script is taking too long to run, restart the Database server instance by opening Control Panel > Administrative Tools > Services >