Monday, December 17, 2007

Description

Reliance Standard Life Insurance Company (Reliance Standard) is a leading insurance carrier specializing in innovative and flexible employee benefits solutions including disability income and group term life insurance. Reliance Standard Life Insurance Company provides insurance products and services in all states (except New York), the District of Columbia, Puerto Rico and the U.S. Virgin Islands. In New York, insurance products and services are provided through First Reliance Standard Life Insurance Company, home office: New York, N.Y. Product availability and features may vary by state. It distributes its products through independent agents and brokers. Main categorization of the products of RSLI is Voluntary & Non-Voluntary products. Non-Voluntary are those products that an employer takes on the behalf of his/her employees in the organization depending upon their individual credentials. Voluntary are those RSLI products that an employee applies for himself/herself without the involvement of employer. Calculation and Posting of Premiums are the most important activities of a RSLI’s product life cycle. RSLI generates bills for their customers to let them show the premium due amount that has to pay against the policies. There are several agents/brokers associated with RSLI countrywide who are responsible to sell the RSLI products. RSLI is also having TPAs to collect the relevant information about the thousands of employees of an organization in one stream at a time. RSLI is also connected with Medical Underwriter companies to undergo the process of medical approval against the claims. RSLI also holds the capability to take over the cases of an organization from some other insurance company with minimal complexity. To provide clarity on the business life cycle, RSLI is providing separate websites for employer and employee in order to deal with their intended specific tasks.

Monday, November 26, 2007

Gen L

using System;using System.Collections.Generic;using System.Text;using Csla;using BAF.Genesis.Biz;
namespace BAF.Genesis.GenericEntities.Biz{ [Serializable()] public abstract class GenericEntityListBase : BAFBusinessListBase where T : GenericEntityListBase where C : GenericEntityBase { #region Protected Variables [NotUndoable] protected int _parentID = -1; [NotUndoable] protected int _relationTypeID = -1; #endregion
#region Constructors protected GenericEntityListBase(int parentID, int relationType) { _parentID = parentID; _relationTypeID = relationType; AllowEdit = false; MarkAsChild(); } #endregion
#region Business Properties and Methods
internal void SetParentID(int parentID) { foreach (C child in this) { child.SetParentID(parentID); } _parentID = parentID; }
internal void AssertParentID() { if (_parentID <>

Gen

using System;using System.Collections.Generic;using System.Text;using Csla;using BAF.Genesis.Biz;
namespace BAF.Genesis.GenericEntities.Biz{ [Serializable()] public abstract class GenericEntityBase : BAFBusinessBase where T : GenericEntityBase { #region Private Variables private static int _lastID = -1; #endregion
#region Protected Variables [NotUndoable] protected int _ID = -1; [NotUndoable] protected int _parentID = -1; [NotUndoable] protected int _relationTypeID = -1; #endregion Protected Variables
#region Constructors protected GenericEntityBase(int parentID, int relationType) { _parentID = parentID; _relationTypeID = relationType; MarkAsChild(); } #endregion
#region Business Properties and Methods public int ID { get { return _ID; } }
internal void SetParentID(int parentID) { _parentID = parentID; }
internal void MakeIDNextNewID() { _ID = --_lastID; }
internal void AssertParentID() { if (_parentID <>

Thursday, November 22, 2007

Addresses

using System;using System.Collections.Generic;using System.Text;using Csla.Data;using BAF.Genesis.Biz;using Microsoft.Practices.EnterpriseLibrary.Data;using System.Data;using BAF.Genesis.Common.Biz;using BAF.Caching;
namespace BAF.Genesis.GenericEntities.Biz{ [Serializable()] public class Addresses : GenericEntityListBase { #region Constructors private Addresses(int parentID, int relationType) : base(parentID, relationType) { } #endregion Constructors
#region Business Properties and Methods public Address GetAddressByID(int addressID) { foreach (Address add in this) { if (add.ID == addressID) return add; } return null; } public Address CreateNewAddress() { return Address.NewAddress(_parentID, _relationTypeID, this); }
public Address CreateNewAddress(Address address) { return Address.NewCloneAddress(address, this); }
public new Address AddNew() { Address a = CreateNewAddress(); this.Add(a); return a; }
public Address AddNew(Address address) { Address a = CreateNewAddress(address); this.Add(a); return a; }
public void Remove(int addressID) { Address a = this.GetAddressByID(addressID); this.Remove(a); } #endregion Business Properties and Methods
#region Static Methods
internal static Addresses NewAddresses(int parentID, int relationType) { return new Addresses(parentID, relationType); }
internal static Addresses NewAddresses(int parentID, DBAddressRelationType relationType) { return NewAddresses(parentID, (int)relationType); } #endregion Static Methods
#region Data Access
internal static Addresses GetAddresses(int parentID, int relationType) { Addresses a = new Addresses(parentID, relationType); a.Fetch(); return a; }
internal static Addresses GetAddresses(SafeDataReader dr, int parentID, int relationType) { Addresses a = new Addresses(parentID, relationType); a.Fetch(dr); return a; }
internal static Addresses GetAddresses(int parentID, DBAddressRelationType relationType) { return GetAddresses(parentID, (int)relationType); }
internal static Addresses GetAddresses(SafeDataReader dr, int parentID, DBAddressRelationType relationType) { return GetAddresses(dr, parentID, (int)relationType); }
private void Fetch(SafeDataReader dr) { while (dr.Read()) { this.Add(Address.GetAddress(dr, _parentID, _relationTypeID)); } }
private void Fetch() { try { Database db = DatabaseFactory.CreateDatabase("GenesisDB"); string spName = "ADDRESSP.GETADDRESSTLIST"; System.Data.Common.DbCommand dbCommand = db.GetStoredProcCommand(spName);
db.AddInParameter(dbCommand, "pnParentID", DbType.Int32, _parentID); db.AddInParameter(dbCommand, "pnRelationTypeID", DbType.Int32, _relationTypeID); db.AddInParameter(dbCommand, "pcUserName", DbType.String, UserName); dbCommand.Parameters.Add(new System.Data.OracleClient.OracleParameter("cur_OUT", System.Data.OracleClient.OracleType.Cursor, 2000, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Default, Convert.DBNull));
using (SafeDataReader dr = new SafeDataReader(db.ExecuteReader(dbCommand))) // Automatically closes the DataReader { while(dr.Read()) { this.Add(Address.GetAddress(dr, _parentID, _relationTypeID)); } } } catch (Exception ex) { throw ex; } }
internal void Update(T parent) where T : BAFBusinessBase { if (parent.IsDeleted) {//Delete all Addresses and their relations DeleteAddresses(_parentID, _relationTypeID); return; }
//Delete objects in the deleted list foreach (Address aDeleted in DeletedList) aDeleted.DeleteSelf(); //now that they are deleted, remove them from memory too DeletedList.Clear();
// Update or Insert child objects foreach (Address a in this) { if (a.IsNew) a.Insert(); else a.Update(); } }
internal static void DeleteAddresses(int parentID, int relationType) { Address.DeleteAddress(parentID, relationType); }
internal static void DeleteAddresses(int parentID, DBAddressRelationType relationType) { DeleteAddresses(parentID, (int)relationType); } #endregion Data Access
#region State List
public static State StateList { get { if (!ApplicationCache.Contains("State_StateList")) { State _stateList = State.GetStateList(); ApplicationCache.Add("State_StateList", _stateList); return _stateList; }
return (State)ApplicationCache.GetData("State_StateList"); } } #endregion
#region Country State List
public static State CountryStateList { get { return State.GetStateList(true); } } #endregion
#region Country List
public static Country CountryList { get { if (!ApplicationCache.Contains("Country_CountryList")) { Country _countryList = Country.GetList(new NameValueList.NameValuePair(-1, "[No Data]"), new NameValueList.NameValuePair(-1, "[Select Country]")); ApplicationCache.Add("Country_CountryList", _countryList); return _countryList; } return (Country)ApplicationCache.GetData("Country_CountryList"); } } #endregion
#region Public Methods public new void BeginEdit() { foreach (Address address in this) address.BeginEdit(); }
public new void ApplyEdit() { foreach (Address address in this) address.ApplyEdit(); }
public new void CancelEdit() { foreach (Address address in this) address.CancelEdit(); } #endregion }}

Address

using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.OracleClient;using BAF.Genesis.Common.Biz;using BAF.Caching;using Csla.Data;using Microsoft.Practices.EnterpriseLibrary.Data;using System.Threading;using Csla.Validation;using Csla;
namespace BAF.Genesis.GenericEntities.Biz{ [Serializable()] public class Address : GenericEntityBase
{ #region Member Variables private int _addressTypeID = -1; private string _addressLine1 = string.Empty; private string _addressLine2 = string.Empty; private string _city = string.Empty; private int _state = -1; private string _zip = string.Empty; private int _country = 1; private bool _isPrimary = false; [NotUndoable()] [NonSerialized()] private Addresses _tmpParentCollection = null; #endregion Member Variables
#region Constants
/// /// StateID used for invalid state /// public const int CONST_INVALID_STATE_ID = -2;
#endregion Constants
#region Constructors private Address(int parentID, int relationType, Addresses addresses) : base(parentID, relationType) { _tmpParentCollection = addresses; _entityName = "Address"; }
private Address(int parentID, int relationType) : base(parentID, relationType) { _entityName = "Address"; } #endregion
#region Business Properties and Methods
public int AddressTypeID { get { return _addressTypeID; } set { if (_addressTypeID != value) { _addressTypeID = value; PropertyHasChanged(); } } }
public string AddressTypeName { get { return AddressTypes.Value(_addressTypeID); } }
public string AddressLine1 { get { return _addressLine1; } set { value = value.Trim(); if (_addressLine1 != value) { _addressLine1 = value; PropertyHasChanged(); } } }
public string AddressLine2 { get { return _addressLine2; } set { value = value.Trim(); if (_addressLine2 != value) { _addressLine2 = value; PropertyHasChanged(); } } }
public string City { get { return _city; } set { value = value.Trim(); if (_city != value) { _city = value; PropertyHasChanged(); } } } public int State { get { return _state; } set { if (_state != value) { _state = value; PropertyHasChanged(); } } }
public string StateName { get { return Addresses.StateList.Value(_state); } }
public string Zip { get { return _zip; } set { value = value.Trim(); if (_zip != value) { _zip = value; PropertyHasChanged(); } } }
public int Country { get { return _country; } set { if (_country != value) { _country = value; _state = -1; PropertyHasChanged(); } } }
public bool IsPrimary { get { return _isPrimary; } set { if (_isPrimary != value) { _isPrimary = value; PropertyHasChanged(); } } }
/// /// Gets Parent Collection /// private Addresses ParentCollection { get { return (base.Parent != null ? (Addresses)base.Parent : _tmpParentCollection); } }
public override bool IsValid { get { return base.IsValid; } } #endregion Business Properties and Methods
#region Override Methods protected override object GetIdValue() { return _ID; } #endregion Override Methods
#region Static Methods public static Address NewAddress(int parentID, int relationType, Addresses addresses) { Address a = new Address(parentID, relationType, addresses); a.MakeIDNextNewID(); return a; }
public static Address NewAddress(int parentID, DBAddressRelationType relationType, Addresses addresses) { return NewAddress(parentID, (int)relationType, addresses); }
public static Address NewAddress(int parentID, DBAddressRelationType relationType) { Address a = new Address(parentID, (int)relationType); a.MakeIDNextNewID(); return a; }
public static Address NewCloneAddress(Address address, Addresses addresses) { Address ad = address.Clone(); ad.MakeIDNextNewID(); ad._tmpParentCollection = addresses; ad._addressTypeID = -1; ad._isPrimary = false; ad.MarkNew(); return ad;
} #endregion
#region Data Access internal static Address GetAddress(int parentID, int relationType) { Address a = new Address(parentID, relationType); a.Fetch(); return a; }
internal static Address GetAddress(int parentID, DBAddressRelationType relationType) { return GetAddress(parentID, (int)relationType); }
internal static Address GetAddress(SafeDataReader dr, int parentID, int relationType) { Address a = new Address(parentID, relationType); a.Fetch(dr); return a; }
internal static Address GetAddress(SafeDataReader dr, int parentID, DBAddressRelationType relationType) { return GetAddress(dr, parentID, (int)relationType); }
internal void Insert() { // if we're not dirty then don't update the database if (!this.IsDirty) return;
Database db = DatabaseFactory.CreateDatabase("GenesisDB"); string spName = "ADDRESSP.ADDADDRESST"; System.Data.Common.DbCommand dbCommand = db.GetStoredProcCommand(spName);
db.AddInParameter(dbCommand, "pnADDRESSTYPEID", DbType.Int32, _addressTypeID); db.AddInParameter(dbCommand, "pcADDRESSLINE1", DbType.String, _addressLine1); db.AddInParameter(dbCommand, "pcADDRESSLINE2", DbType.String, _addressLine2); db.AddInParameter(dbCommand, "pcCITY", DbType.String, _city); db.AddInParameter(dbCommand, "pnSTATEPROVID", DbType.Int32, (_state <= 0 ? DBNull.Value : (object)_state)); db.AddInParameter(dbCommand, "pcZIP", DbType.String, _zip); db.AddInParameter(dbCommand, "pcUsername", DbType.String, UserName); db.AddInParameter(dbCommand, "pnPRIMARYIND", DbType.Int32, _isPrimary ? 1 : 0); db.AddInParameter(dbCommand, "pnParentID", DbType.Int32, _parentID); db.AddInParameter(dbCommand, "pnRelationTypeID", DbType.Int32, _relationTypeID); db.AddOutParameter(dbCommand, "pnID", DbType.Int32, 8); db.ExecuteNonQuery(dbCommand);
_ID = (int)db.GetParameterValue(dbCommand, "pnID");
MarkOld(); }
internal void Insert(T obj) { // if we're not dirty then don't update the database if (!this.IsDirty) return;
Database db = DatabaseFactory.CreateDatabase("GenesisDB"); string spName = "ADDRESSP.ADDADDRESST"; System.Data.Common.DbCommand dbCommand = db.GetStoredProcCommand(spName);
db.AddInParameter(dbCommand, "pnADDRESSTYPEID", DbType.Int32, _addressTypeID); db.AddInParameter(dbCommand, "pcADDRESSLINE1", DbType.String, _addressLine1); db.AddInParameter(dbCommand, "pcADDRESSLINE2", DbType.String, _addressLine2); db.AddInParameter(dbCommand, "pcCITY", DbType.String, _city); db.AddInParameter(dbCommand, "pnSTATEPROVID", DbType.Int32, (_state <= 0 ? DBNull.Value : (object)_state)); db.AddInParameter(dbCommand, "pcZIP", DbType.String, _zip); db.AddInParameter(dbCommand, "pcUsername", DbType.String, UserName); db.AddInParameter(dbCommand, "pnPRIMARYIND", DbType.Int32, _isPrimary ? 1 : 0); db.AddInParameter(dbCommand, "pnParentID", DbType.Int32, _parentID); db.AddInParameter(dbCommand, "pnRelationTypeID", DbType.Int32, _relationTypeID); db.AddOutParameter(dbCommand, "pnID", DbType.Int32, 8); db.ExecuteNonQuery(dbCommand);
_ID = (int)db.GetParameterValue(dbCommand, "pnID");
MarkOld(); }
internal void Update() { // if we're not dirty then don't update the database if (!this.IsDirty) return;
Database db = DatabaseFactory.CreateDatabase("GenesisDB"); string spName = "ADDRESSP.UPDATEADDRESST"; System.Data.Common.DbCommand dbCommand = db.GetStoredProcCommand(spName);
db.AddInParameter(dbCommand, "pnID", DbType.Int32, _ID); db.AddInParameter(dbCommand, "pnADDRESSTYPEID", DbType.Int32, _addressTypeID); db.AddInParameter(dbCommand, "pcADDRESSLINE1", DbType.String, _addressLine1); db.AddInParameter(dbCommand, "pcADDRESSLINE2", DbType.String, _addressLine2); db.AddInParameter(dbCommand, "pcCITY", DbType.String, _city); db.AddInParameter(dbCommand, "pnSTATEPROVID", DbType.Int32, (_state <= 0 ? DBNull.Value : (object)_state)); db.AddInParameter(dbCommand, "pcZIP", DbType.String, _zip); db.AddInParameter(dbCommand, "pnPRIMARYIND", DbType.Int32, _isPrimary ? 1 : 0); db.AddParameter(dbCommand, "pnObjectVersion", DbType.Int32, ParameterDirection.InputOutput, null, DataRowVersion.Default, _objectVersion); db.AddInParameter(dbCommand, "pcForceUpdate", DbType.String, (_isForceUpdate ? "Y" : "N")); db.AddInParameter(dbCommand, "pcUsername", DbType.String, BizHelper.UserName); db.ExecuteNonQuery(dbCommand);
MarkOld(); }
internal void Update(T obj) { // if we're not dirty then don't update the database if (!this.IsDirty) return;
Database db = DatabaseFactory.CreateDatabase("GenesisDB"); string spName = "ADDRESSP.UPDATEADDRESST"; System.Data.Common.DbCommand dbCommand = db.GetStoredProcCommand(spName);
db.AddInParameter(dbCommand, "pnID", DbType.Int32, _ID); db.AddInParameter(dbCommand, "pnADDRESSTYPEID", DbType.Int32, _addressTypeID); db.AddInParameter(dbCommand, "pcADDRESSLINE1", DbType.String, _addressLine1); db.AddInParameter(dbCommand, "pcADDRESSLINE2", DbType.String, _addressLine2); db.AddInParameter(dbCommand, "pcCITY", DbType.String, _city); db.AddInParameter(dbCommand, "pnSTATEPROVID", DbType.Int32, (_state <= 0 ? DBNull.Value : (object)_state)); db.AddInParameter(dbCommand, "pcZIP", DbType.String, _zip); db.AddInParameter(dbCommand, "pnPRIMARYIND", DbType.Int32, _isPrimary ? 1 : 0); db.AddParameter(dbCommand, "pnObjectVersion", DbType.Int32, ParameterDirection.InputOutput, null, DataRowVersion.Default, _objectVersion); db.AddInParameter(dbCommand, "pcForceUpdate", DbType.String, (_isForceUpdate ? "Y" : "N")); db.AddInParameter(dbCommand, "pcUsername", DbType.String, BizHelper.UserName); db.ExecuteNonQuery(dbCommand);
MarkOld(); }
internal void DeleteSelf() { // if we're not dirty then don't update the database if (!this.IsDirty) return;
// if we're new then don't update the database if (this.IsNew) return;
Database db = DatabaseFactory.CreateDatabase("GenesisDB"); string spName = "ADDRESSP.DELETEADDRESST"; System.Data.Common.DbCommand dbCommand = db.GetStoredProcCommand(spName); db.AddInParameter(dbCommand, "pcUsername", DbType.String, BizHelper.UserName); db.AddInParameter(dbCommand, "pnID", DbType.Int32, _ID); db.ExecuteNonQuery(dbCommand);
MarkOld(); }
private void Fetch(SafeDataReader dr) { _ID = dr.GetInt32("ID"); _addressTypeID = dr.GetInt32("ADDRESSTYPEID"); _addressLine1 = dr.GetString("ADDRESSLINE1"); _addressLine2 = dr.GetString("ADDRESSLINE2"); _city = dr.GetString("CITY"); _zip = dr.GetString("ZIP"); _state = dr.GetInt32("STATE"); _country = dr.GetInt32("COUNTRY"); _isPrimary = dr.GetBoolean("PRIMARYIND");
MarkOld(); }
internal static void DeleteAddress(int parentID, int relationType) { Database db = DatabaseFactory.CreateDatabase("GenesisDB"); string spName = "ADDRESSP.DELETEADDRESSTLIST"; System.Data.Common.DbCommand dbCommand = db.GetStoredProcCommand(spName);
db.AddInParameter(dbCommand, "pnParentID", DbType.Int32, parentID); db.AddInParameter(dbCommand, "pnRelationTypeID", DbType.Int32, relationType); db.AddInParameter(dbCommand, "pcUserName", DbType.String, BizHelper.UserName); db.ExecuteNonQuery(dbCommand); }
internal static void DeleteAddress(int parentID, DBAddressRelationType relationType) { DeleteAddress(parentID, (int)relationType); }
private void Fetch() { try { Database db = DatabaseFactory.CreateDatabase("GenesisDB"); string spName = "ADDRESSP.GETADDRESST"; System.Data.Common.DbCommand dbCommand = db.GetStoredProcCommand(spName);
db.AddInParameter(dbCommand, "pnParentID", DbType.Int32, _parentID); db.AddInParameter(dbCommand, "pnRelationTypeID", DbType.Int32, _relationTypeID); db.AddInParameter(dbCommand, "pcUsername", DbType.String, UserName); dbCommand.Parameters.Add(new System.Data.OracleClient.OracleParameter("cur_OUT", System.Data.OracleClient.OracleType.Cursor, 2000, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Default, Convert.DBNull));
using (SafeDataReader dr = new SafeDataReader(db.ExecuteReader(dbCommand))) // Automatically closes the DataReader { if (dr.Read()) { Fetch(dr); } else MarkOld(); } } catch (Exception ex) { throw ex; } } #endregion
#region Methods
public static bool IsDuplicate(object target, RuleArgs e) { Address add = (Address)target; if (add.ParentCollection == null) return true;
foreach (Address ad in add.ParentCollection) { if (ad.ID != add._ID) { if (ad.AddressTypeID == add._addressTypeID && (String.Compare(ad.AddressLine1, add._addressLine1, true) == 0) && (String.Compare(ad.AddressLine2, add._addressLine2, true) == 0) && (String.Compare(ad.City, add._city, true) == 0) && ad.State == add._state && (String.Compare(ad.Zip, add._zip, true) == 0) && ad.Country == add._country) { e.Description = "Address already exists."; return false; } } }
return true; } #endregion
#region AddressTypeList public static AddressTypeList AddressTypes { get { if (!ApplicationCache.Contains("Address_AddressTypes")) { AddressTypeList addTypeList = AddressTypeList.GetList(); ApplicationCache.Add("Address_AddressTypes", addTypeList); return addTypeList; }
return (AddressTypeList)ApplicationCache.GetData("Address_AddressTypes"); } } #endregion AddressTypeList
#region Business Rules protected override void AddBusinessRules() { ValidationRules.AddRule(IntegerRequired, new BunchRuleArgs("AddressTypeID", "Address Type")); ValidationRules.AddRule(StringRequired, new BunchRuleArgs("AddressLine1", "Address Line 1")); ValidationRules.AddRule(StringRequired, new BunchRuleArgs("City", "City")); ValidationRules.AddRule(IntegerRequired, new BunchRuleArgs("State", "State")); ValidationRules.AddRule(StringRequired, new BunchRuleArgs("Zip", "Zip")); ValidationRules.AddRule(StringMaxLength, new BunchMaxLengthRuleArgs("AddressLine1", "Address Line 1", 40)); ValidationRules.AddRule(StringMaxLength, new BunchMaxLengthRuleArgs("AddressLine2", "Address Line 2", 40)); ValidationRules.AddRule(StringMaxLength, new BunchMaxLengthRuleArgs("City", "City", 30)); ValidationRules.AddRule(StringMaxLength, new BunchMaxLengthRuleArgs("Zip", "Zip", 10));
ValidationRules.AddRule(ValidateState, new RuleArgs("State")); ValidationRules.AddRule(IsDuplicate, new RuleArgs("IsValid")); }
public override void ValidatePrimary() { if (IsPrimary) { foreach (Address obj in ParentCollection) obj.IsPrimary = (obj.ID == ID); } }
private static bool ValidateState(object target, RuleArgs e) { if (((Address)target)._state == CONST_INVALID_STATE_ID) { e.Description = "State is invalid."; return false; } return true; }
#endregion }}

Thursday, October 11, 2007

Can't delete column from a table (SQL SERVER 2000)

I was working on Sql server 2000 which was migrated from older version to sql server 2000.

I have added a column to an existing table using the following query:

alter table test add col1 varchar(1)

And afterwards I wanted to delete that column. I have tried the following query for that

alter table [test] drop column [col1]

but its always giving me the following error message :

This query executed successfully.

'test' table

- Unable to modify table.

ODBC error: [Microsoft][ODBC SQL Server Driver][SQL Server]Line 2: Incorrect syntax near 'col1'.

 

Same error I was getting when I tried deleting the column from Enterprise Manager.

Resolution :

first run the following query & check the compatibility :

sp_dbcmptlevel databaseName

If the compatability level is 65, change it to 70 or 80 by using the following query:

sp_dbcmptlevel databaseName,70

 

Now the delete query will be executed without fail.

Calling functions in C#.NET dll from C++

Create a C#.NET class Library :
Paste the below code in the class file and build it.
---------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace strEncrypt
{
    public class clsEncrypt
    {
        public string EncryptString(string input)
        {
            try
            {
                System.Text.UnicodeEncoding encoding = new UnicodeEncoding();
                System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

                byte[] byteVal = encoding.GetBytes(input);
                byte[] byteencryptedPwd = sha1.ComputeHash(byteVal);
                sha1.Clear();
                string pwd = Convert.ToBase64String (byteencryptedPwd);

                try
                {
                    StreamWriter sw = new StreamWriter(@"C:\Password.txt");
                    sw.WriteLine(pwd);
                    sw.Close();
                }
                catch
                {
                    //Apart from returning the encrypted string, I am also writing the same to C:\Password.txt.
                }
                return pwd;
            }
            catch
            {
                return "EXCEPTION";
            }
        }
    }
}
---------------------------------------------------------------------------------

Now we will get a C#.NET dll and now let me explain you how to consume this in C++ application.

---------------------------------------------------------------------------------

Create a new project from Visual studio :

Project Types : Visual C++ -> Win32 -> Win32 Console application. Click on OK after entering the file name.

Now we will get Win32 Applicatio Wizard. Click on Next.

Select 'Console Application' and click on finish.

---------------------------------------------------------------------------------

Copy the dll into our C++ project folder.

Open 'Property Pages' of the project. From Common Properties -> References , click on 'Add new reference' and add the C#.NET dll reference.

From the same window  'Configuration Properties' ->

General :

Character Set : Not set

Common Language Runtime support - select 'Common Language Runtime Support (/clr)'

C/C++ : Debug Information format : Disabled

             Warning Level : Level1

             Detect 64 bit portability issues : No

---------------------------------------------------------------------------------

code for .cpp file

---------------------------------------------------------------------------------

#include <iostream>
#using <mscorlib.dll>
#using <strEncryptCS.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Security::Cryptography;
using namespace std;
using namespace strEncrypt;

System::String^ CPPEncryptString(System::String^);

void main(int argc, char *argv[])
{
 
 System::String^ input;
 System::String^ output;
 Console::WriteLine("Enter String:");
 input=Console::ReadLine();
 output = CPPEncryptString(input);
 Console::WriteLine(output);
 Console::Read();
}

System::String^ CPPEncryptString(System::String^ input)
{
 clsEncrypt a;
 return a.EncryptString(input);
}

---------------------------------------------------------------------------------

Build this application. You will get an exe.

 

This is how we can access & use functions C#.NET dll in C++.

 

 

 

Sunday, September 23, 2007

Stored Procedures Cache

The stored procedure cache is an area of memory where SQL Server keeps the compiled execution plans. Once a stored procedure has been executed, the execution remains in memory, so the subsequent users, each with a different execution context (including parameters and variables) can share one copy of the procedure in memory. SQL Server 2000 has one unified cache, where it stores data pages with the stored procedures and queries plans. Because SQL Server 2000 can dynamically allocate more memory when it is needed, the execution plan can stay in the cache as long as it is useful. However, if there is not enough memory for the current SQL Server work, the older plans could be deleted from the cache to free up memory.
Each execution plan has an associated cost factor that indicates how expensive the structure is to compile. The more expensive the stored procedure is to compile, the larger the associated cost factor it will have, and vice versa. Each time the stored procedure is referenced by a connection, its cost factor is incremented. Therefore, a cached plan can have a big cost factor when the object is referenced by a connection very frequently or when recreation of the execution plan is very expensive. The lazywriter process is responsible for determining whether to free up the memory the cache is using, or keep the plan in cache. This process periodically scans the list of objects in the procedure cache. If the cost of a buffer is greater than zero when the lazywriter inspects it, the lazywriter decrements the cost factor by one.
Every time a cached plan is reused, its cost reverts to its original value. The lazywriter process deletes the execution plan from the cache when the following three conditions are met:
The memory is required for other objects and all available memory is currently in use.
The cost factor for the cached plan is equal to zero.
The stored procedure is not currently referenced by a connection.
The frequently referenced stored procedures do not have their cost factor decremented to zero and are not aged from the cache. Even though the plan's cost factor will be equal to zero, it will stay in cache unless memory is required for other objects.
When you tune your stored procedures to maximize performance, you may want to clear the stored procedures cache to ensure fair testing. In this case, you can use the DBCC FREEPROCCACHE statement to clear the procedure cache.

Wednesday, September 12, 2007

Can't Delete a Column from SQL Server

I was working on Sql server 2000 which was migrated from older version to sql server 2000. I have added a column to an existing table using the following query: alter table test add col1 varchar(1) And afterwards I wanted to delete that column. I have tried the following query for that alter table [test] drop column [col1] but its always giving me the following error message : This query executed successfully. 'test' table - Unable to modify table. ODBC error: [Microsoft][ODBC SQL Server Driver][SQL Server]Line 2: Incorrect syntax near 'col1'. Same error I was getting when I tried deleting the column from Enterprise Manager. Resolution : first run the following query & check the compatibility : sp_dbcmptlevel databaseName If the compatability level is 65, change it to 70 or 80 by using the following query: sp_dbcmptlevel databaseName,70 Now the delete query will be executed without fail.

Friday, September 7, 2007

Upload File

IOTool webIOTool = new IOTool();
FileStream liveStream = new FileStream(fdAttachement.FileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[(int)liveStream.Length];
liveStream.Read(buffer, 0, (int)liveStream.Length);
liveStream.Close();
webIOTool.CreateAttachment(CT.GetConfigVal("TaskAttachmentPath") + fileName, buffer);




public class IOTool : System.Web.Services.WebService
{
#region Web Methods
///
/// Creates the file.
///

/// The File Path
/// Empty string or error message if any
[WebMethod]
public string CreateAttachment(string destFilePath, byte[] buffer)
{
try
{
Stream istream;
istream = File.Create(destFilePath);
istream.Write(buffer, 0, buffer.GetUpperBound(0));
istream.Flush();
istream.Close();
}
catch (Exception ex)
{
return ex.Message;
}
return string.Empty;
}

}

Wednesday, September 5, 2007

Loading and Saving File

OpenFileDialog fdAttachement = new OpenFileDialog();
fdAttachement.Filter = "All Files (*.*)*.*Text files (*.txt)*.txtWord Files (*.doc)*.docExcel Files (*.xls)*.xlsPDF Files (*.pdf)*.pdfImage Files(*.jpg,*.gif)*.jpg;*.gif";
//fdAttachement.InitialDirectory = "";
fdAttachement.DefaultExt = "*.*";
if (fdAttachement.ShowDialog(this) == DialogResult.Cancel)
return;
FileInfo fileInfo = new FileInfo(fdAttachement.FileName);
string[] fullName;
string fileName;
fullName = fdAttachement.FileName.Split('\\');
fileName = fullName[fullName.Length - 1];
fileInfo.CopyTo(CT.GetConfigVal("TempTaskAttachmentPath") + fileName, true);

Monday, September 3, 2007

How to open file

System.Diagnostics.Process.Start(strFileName);

Monday, August 27, 2007

Add filter to Open File Dialog

fdlgOpenAttachments = new OpenFileDialog();

fdlgOpenAttachments.Filter = "All Files (*.*)*.*Text files (*.txt)*.txtWord Files (*.doc)*.docExcel Files (*.xls)*.xlsPDF Files (*.pdf)*.pdfImage Files(*.jpg,*.gif)*.jpg;*.gif";

Thursday, July 26, 2007

Caching in window applications

///
/// This is the object to use to cache low volitality data
///

///
///
///
///
public sealed class ApplicationCache
{
///
/// Empty private constructor
/// Static holder types should not have constructors
///

///
private ApplicationCache()
{
}
///
/// Use this to add to the cache
///

/// This is the key for the value to add to the cache
/// This is the value to add to the cache
public static void Add(string key, object value)
{
try
{
CacheManager myManager = CacheFactory.GetCacheManager();
if (!myManager.Contains(key))
myManager.Add(key, value);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Use this to retreive from the cache
///

/// This is the key for the value to retrieve from the cache
/// Returns an object, developer must cast this properly!
public static object GetData(string key)
{
try
{
CacheManager myManager = CacheFactory.GetCacheManager();
return myManager.GetData(key); ;
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Use this to remove items from the cache
///

/// This is the key for the value to remove from the cache
/// Returns nothing
public static void RemoveData(string key)
{
try
{
CacheManager myManager = CacheFactory.GetCacheManager();
myManager.Remove(key);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Use this to query from the cache for a key/value pair
///

/// This is the key for the value to retrieve from the cache
/// Returns a boolean
public static bool Contains(string key)
{
try
{
CacheManager myManager = CacheFactory.GetCacheManager();
return myManager.Contains(key);
}
catch (Exception ex)
{
throw ex;
}
}
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



if (!ApplicationCache.Contains("User_Departments"))
{

// Go to databse and get the object.
ApplicationCache.Add("User_Departments", _departments);
}
return (DepartmentList)ApplicationCache.GetData("User_Departments");


Tuesday, July 17, 2007

Select Condition 1

CREATE TABLE #Temp (ids INT)

INSERT INTO #Temp VALUES (1)
INSERT INTO #Temp VALUES (2)
INSERT INTO #Temp VALUES (3)
INSERT INTO #Temp VALUES (4)
INSERT INTO #Temp VALUES (5)

Condition :
If I pass parameter as -1 it should return records having ids 1 or 3.
If I pass parameter as 5 it should return only records having ids 5.

DECLARE @a INT
--SET @a = -1
SET @a = 5

SELECT * FROM #Temp WHERE ((ids = 1 OR ids = 3) AND @a = -1) OR ids = @a

Friday, July 13, 2007

Interface Example1

interface ISample1
{
int sum();
}
interface ISample2
{
int sum();
}
public class A : ISample1, ISample2
{
// There should be no access specifier (it will give build error).
int ISample1.sum()
{
return 10;
}
// There should be no access specifier (it will give build error).
int ISample2.sum()
{
return 20;
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
ISample1 is1 = (ISample1)a;
Console.WriteLine(is1.sum().ToString());
ISample2 is2 = (ISample2)a;
Console.WriteLine(is2.sum().ToString());
}
}

Thursday, July 12, 2007

Polymorphism Example 5

public class A
{
public virtual void Print(int count)
{
Console.WriteLine(count.ToString() + " We are in A");
}
}
public class B : A
{
public override void Print(int count)
{
Console.WriteLine(count.ToString() + " We are in B");
}
public void Print(double count)
{
Console.WriteLine(count.ToString() + " Hi Kumar.");
}
}
class Program
{
static void Main(string[] args)
{
B b = new B();
b.Print(5); // 5 Hi kumar
((A)b).Print(5); // 5 We are in B
Console.ReadKey();
A a = new A();
a.Print(5); // 5 We are in A
Console.ReadKey();
A aa = new B();
aa.Print(5); // 5 We are in B
Console.ReadKey();
}
}

Polymorphism Example 4

class A
{
public virtual void Print()
{
Console.WriteLine("We are in Class A.");
}
}
class C : A
{
public new void Print()
{
Console.WriteLine("We are in Class C.");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Print();
Console.ReadKey();
C c = new C();
c.Print();
Console.ReadKey();
A aa = new C();
aa.Print();
Console.ReadKey();
A aaa = (A)c;
aaa.Print();
Console.ReadKey();
//C ccc = (C)a;
//ccc.Print();
//Console.ReadKey();
}
}

Polymorphism Example 3

public class A
{
public void PrintA()
{
Console.WriteLine("We are in class A");
}
}
public class B : A
{
public void PrintB()
{
Console.WriteLine("We are in class B");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
a.writeA();
Console.ReadKey();
// Following code will give RUNTIME error.
B b = (B)a;
b.writeA();
b.writeB();
Console.ReadKey();
////////////////////////////////////////////
B bb = new B();
bb.writeA();
bb.writeB();
Console.ReadKey();
A aa = (A)bb;
aa.writeA();
Console.ReadKey();
}
}

Polymorphism Example 2

class A
{
public virtual void Print()
{
Console.WriteLine("We are in Class A");
}
}
class B : A
{
public override void Print()
{
Console.WriteLine("We are in Class B.");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Print();
Console.ReadKey();
B b = new B();
b.Print();
Console.ReadKey();
A aa = new B();
aa.Print();
Console.ReadKey();
// Following code will give build error
//B bb = new A();
//b.Print();
//Console.ReadKey();
///////////////////////////////////////
A aaa = (A)b;
aaa.Print();
Console.ReadKey();
// Following code will give RUNTIME error
B bbb = (B)a;
bbb.Print();
Console.ReadKey();
}
}

Polymorphism Example 1

public class A : Object
{
public void writeA()
{
Console.WriteLine("This class A");
}
}
public class B : A
{
public void writeB()
{
Console.WriteLine("This class B");
}
}
class Program
{
static void Main(string[] args)
{
A objA = new A();
objA.writeA();
Console.ReadKey();
B objB = new B();
objB.writeA();
objB.writeB();
Console.ReadKey();
A objAB = new B();
objAB.writeA();
Console.ReadKey();
// Following Code will give (Build)error.
//B objBA = new A();
//objBA.writeA();
//objBA.writeB();
}
}

Wednesday, July 4, 2007

Add To Favourates

window.external.AddFavorite(location.href, document.title);

Tuesday, July 3, 2007

Assigning Header to Infragistics grid

private void ApplyStylesToGrid()
{
// In 2.0
dgSample.DisplayLayout.Bands[0].Columns[0].Header.Caption = "Customer Id";
dgSample.DisplayLayout.Bands[0].Columns[1].Header.Caption = "Customer Name";
dgSample.DisplayLayout.Bands[1].Columns[0].Header.Caption = "Order Id";
dgSample.DisplayLayout.Bands[1].Columns[1].Header.Caption = "Customer Id";
dgSample.DisplayLayout.Bands[1].Columns[2].Header.Caption = "Order Date";
// In 1.1
//dgSample.DisplayLayout.Bands[0].Columns[0].HeaderText = "Customer Id";
//dgSample.DisplayLayout.Bands[0].Columns[1].HeaderText = "Customer Name";
//dgSample.DisplayLayout.Bands[1].Columns[0].HeaderText = "Order Id";
//dgSample.DisplayLayout.Bands[1].Columns[1].HeaderText = "Customer Id";
//dgSample.DisplayLayout.Bands[1].Columns[2].HeaderText = "Order Date";
}
protected void dgSample_ExpandRow(object sender, RowEventArgs e)
{
dgSample.ExpandAll(false);
e.Row.Expand(true);
}

Tuesday, June 26, 2007

Implementing Transactions in C#.Net

System.Data.SqlClient.SqlConnection sqlCon;
System.Data.SqlClient.SqlTransaction sqlTran;


save()
{
try
{
sqlCon = new SqlConnection(CommonFunctions.connectionString);
sqlCon.Open();
sqlTran = sqlCon.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
//----------------------------

//----------------------------
// Insertion code
// While inserting use sqlTran in place of normal connection string.
//----------------------------

//----------------------------
sqlTran.Commit();
}
catch(SqlException sqlEx)
{
sqlTran.Rollback();
throw new Exception(sqlEx.Message, sqlEx.InnerException);
}
catch(Exception SaveEx)
{
throw new Exception(SaveEx.Message, SaveEx.InnerException);
}
finally
{
sqlTran.Dispose();
sqlCon.Dispose();
}

}

Monday, June 18, 2007

Cursor Syntax

DECLARE curEmp CURSOR FOR SELECT EmpID FROM Employee
OPEN curEmp
FETCH NEXT FROM curEmp INTO @EmpID
WHILE(@@FETCH_STATUS = 0)
BEGIN
-----
-----
-----
END
CLOSE curEmp
DEALLOCATE curEmp

Sunday, June 17, 2007

Insert into IDENTITY Column

SET IDENTITY_INSERT
Allows explicit values to be inserted into the identity column of a table.
Syntax
SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON OFF }
Arguments
database
Is the name of the database in which the specified table resides.
owner
Is the name of the table owner.
table
Is the name of a table with an identity column.
Remarks
At any time, only one table in a session can have the IDENTITY_INSERT property set to ON. If a table already has this property set to ON, and a SET IDENTITY_INSERT ON statement is issued for another table, Microsoft® SQL Server™ returns an error message that states SET IDENTITY_INSERT is already ON and reports the table it is set ON for.
If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.
The setting of SET IDENTITY_INSERT is set at execute or run time and not at parse time.

Thursday, June 14, 2007

Abstract Class vs Interface

I am assuming you are having all the basic knowledge of abstract and interface keyword. I am just briefing the basics.
We can not make instance of Abstract Class as well as Interface.
Here are few differences in Abstract class and Interface as per the definition.
Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).
Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.

//Abstarct Class
public abstract class Vehicles
{
private int noOfWheel;
private string color;
public abstract string Engine
{
get;
set;
}
public abstract void Accelerator();
}
//Interface
public interface Vehicles
{
string Engine
{
get;
set;
}
void Accelerator();
}

We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed.
We use abstract class and Interface for the base class in our application.

This is all about the language defination. Now million doller question:
How can we take decision about when we have to use Interface and when Abstract Class.
Basicly abstact class is a abstract view of any realword entity and interface is more abstract one. When we thinking about the entity there are two things one is intention and one is implemntation. Intention means I know about the entity and also may have idea about its state as well as behaviour but don’t know about how its looks or works or may know partially. Implementation means actual state and behaviour of entity.
Enough theory lets take an example.
I am trying to make a Content Management System where content is a genralize form of article, reviews, blogs etc.


CONTENT
Publish ()

CONTENT

ARTICLE

BLOGS

REVIEW


So content is our base class now how we make a decision whether content class should be Abstract class, Interface or normal class.
First normal class vs other type (abstract and interface). If content is not a core entity of my application means as per the business logic if content is nothing in my application only Article, Blogs, Review are the core part of business logic then content class should not be a normal class because I’ll never make instance of that class. So if you will never make instance of base class then Abstract class and Interface are the more appropriate choice.
Second between Interface and Abstract Class.
CONTENT
Publish ()

ARTICLE

BLOGS

REVIEW

As you can see content having behavior named “Publish”. If according to my business logic Publish having some default behavior which apply to all I’ll prefer content class as an Abstract class. If there is no default behavior for the “Publish” and every drive class makes their own implementation then there is no need to implement “Publish” behavior in the base case I’ll prefer Interface.
These are the in general idea of taking decision between abstract class, interface and normal class. But there is one catch. As we all know there is one constant in software that is “CHANGE”. If I made content class as Interface then it is difficult to make changes in base class because if I add new method or property in content interface then I have to implement new method in every drive class. These problems will over come if you are using abstract class for content class and new method is not an abstract type. So we can replace interface with abstract class except multiple inheritance.
CAN-DO and IS-A relationship is also define the deference between Interface and abstract class. As we already discuss Interface can be use for multiple inheritance for example we have another interface named “ICopy” which having behavior copy and every drive class have to implements its own implementation of Copy. If “Article” class drive from abstract class Content as well as ICopy then article “CAN-DO” copy also.
IS-A is for “generalization” and “specialization” means content is a generalize form of Article, Blogs, Review and Article, Blogs, Review are a specialize form of Content.
So, abstract class defines core identity. If we are thinking in term of speed then abstract is fast then interface because interface requires extra in-direction. So as per my view Abstract class having upper-hand in compare to interface. Using interface having only advantage of multiple inheritance. If you don’t understand the things then don’t worry because it’s my mistake because I am not able to describe the topic.

Wednesday, May 23, 2007

Get name of day in SQL server

SELECT DATENAME(WEEKDAY, GETDATE())

Monday, May 7, 2007

Tree view recursion method


private void AddNodetoComponentTree(UltraTreeNode node)
{
node.Expanded = true;
List childNodes = new List();
childNodes = GetChildNodes(Convert.ToInt32(node.Key));
foreach (ComponentData childNode in childNodes)
{
AddNodetoComponentTree(node.Nodes.Add(childNode.ComponentId.ToString(), childNode.Name));
}
}


private List GetChildNodes(int componentId)
{
List childNodes = new List();
foreach (ComponentData childNode in componentsData)
{
if (childNode.ParentId == componentId && childNode.ComponentId != componentId)
{
childNodes.Add(childNode);
}
}
return childNodes;
}

Friday, March 2, 2007

Reseed Identity Value

DBCC CHECKIDENT

Checks the current identity value for the specified table and, if needed, corrects the identity value.


Syntax:
DBCC CHECKIDENT ( 'table_name' [ , { NORESEED { RESEED [ , new_reseed_value ] } } ] )


Example:

This example forces the current identity value in the jobs table to a value of 30.
USE pubsGO DBCC CHECKIDENT (jobs, RESEED, 30)GO