Thursday 11 August 2016

Open model pop up using jQuery

<div dir="ltr" style="text-align: left;" trbidi="on">
<!-- Start POP for SYNC PNR -->
     <br />
<div class="colum2">
<input class="new_crm_search_btn_beige" id="btnRemarks" name="btnViewDetails" onclick="return ShowModalPopup()" type="button" value="View Details" />
     </div>
<asp:panel cssclass="modalPopup" id="pnlStudent" runat="server">
        <asp:updatepanel id="UpdatePanel1" runat="server">
            <contenttemplate>
                <asp:imagebutton id="ImageButton1" imageurl="~/CRM/Images/fancy_close.png" onclientclick="return HideModalPopup();" runat="server" style="position: absolute; right: -11px; top: -13px;"></asp:imagebutton>
            </contenttemplate>
        </asp:updatepanel>
        </asp:panel><br />
<div class="booking_con scroll_class_popup" style="background-color: white;">
<h3 class="yellow_heading">
</h3>
<div class="padding_con_1">
<div class="row_1">
<h2>
                        ABC
                    </h2>
</div>
<div class="row_1">
<div class="col5">
<sup>*</sup> Name
                        <br />
<div class="passanger_inp_con">
<div class="input_wrapar_search">
<asp:textbox cssclass="Select" id="txtNAme" placeholder="Name" runat="server"></asp:textbox>
                             
                            </div>
</div>
</div>
<div class="col6">
<sup>*</sup>Mobile
                        <br />
<div class="passanger_inp_con">
<div class="input_wrapar_search">
<asp:textbox cssclass="Select" id="txtMobile" placeholder="Mobile" runat="server"></asp:textbox>
                           
                            </div>
</div>
</div>
</div>
<div class="row_1">
<div class="col2 float_R">
<div class="passanger_inp_con">
<div class="input_wrapar_search">
<input class="search_btn_beige" id="btnSubmit" onclick="return Validate()" style="padding: 0px;" type="button" value="Submit" />
                            </div>
</div>
</div>
</div>
</div>
</div>
<asp:linkbutton id="lnkpnlSubmit" runat="server"></asp:linkbutton>
    <cc1:modalpopupextender backgroundcssclass="modalBackground" behaviorid="studentPopUp" dropshadow="false" id="ModalPopupExtender1" popupcontrolid="pnlStudent" runat="server" targetcontrolid="lnkpnlSubmit">
    </cc1:modalpopupextender>

 <script type="text/javascript">
            function ShowModalPopup() {
                $('[id$=txtName]').val('');
                $find("studentPopUp").show();
                return false;
            }
            function HideModalPopup() {
                $('[id$=txtName]').val('');
                $find("studentPopUp").hide();
                return false;
            }
         


        </script></div>

Tuesday 5 July 2016

Interface vs Abstract class. The classic confusion

Interface vs Abstract class. The classic confusion
One of the mostly asked question in OOP is about choosing between an Interface and an Abstract class.  These two look pretty similar and it appears as if one could be used instead of another. So, which one should be most appropriate to use to lay out class designs?

These two things are similar, and both talk about abstraction, rather than concrete implementation. Both concepts are interpreted and inherited from the real world. But, there is a small difference in their purpose.

Interface talks about "What" functionality a particular kind of object should have, and, it doesn't care about exactly "How" these functionality should be implemented by the actual objects of those kind.

For example, let us consider a Vehicle object. A vehicle could be of any brand in the world. But, what are the core functionality of a vehicle? What would you expect from a vehicle while you try to purchase one? The very basic things you would expect would be:

It must start
It must run
It must break
It must accelerate
It must stop

So, how would you identify these "very basic" features for any vehicle in the OOP?

You already know it. You create an interface and put these functionality as some method signatures without definition. That is:

interface IVehicle
{
     void Start();
     void Run();
     void Accelerate();
     void Break();
     void Stop();
}

So, this basically describes what are the basic functionality that a vehicle (Any vehicle made by any manufacturer) should have. Now, how these functionality are going to be implemented? Well, It completely depends on the manufacturers. One particular kind of vehicle might start using a Remote control, and another might start with a Key. One might accelerate via an auto gear and another might accelerate via a manual gear. In OOP, these particular implementations are defined by the classes which implements the interface. The interface knows nothing about these concrete implementation and it is quite happy about that.

On the other hand, an "Abstract class" also talks about "What" functionality a particular kind of object should have, but, it may also talk about "How" a particular functionality is implemented.

Need an example? Here you go

Toyota makes cars and of course all of its cars have the very basic functionality that a vehicle should have. So, each car obviously implements the IVehicle interface. For now, let us assume Toyota makes cars based upon only two models, the Camry and theXCorolla. So, while laying out the Camry and XCorolla classes, they implement the IVehicle classes as follows:

class Camry : IVehicle
{
    public void Start()
    {
         //Starts with a Remote control
    }

    public void Run()
    {
         //Runs via a 2000CC Toyota engine
    }

    public void Accelerate()
    {
         //Accelerates via an Auto gear
    }

    public void Break()
    {
         //Breaks via an hydrolic break
    }

    public void Stop()
    {
         //Stops with a key, or a remote control
    }
}

class XCorolla: IVehicle
{
    public void Start()
    {
         //Starts with a Key

    }

    public void Run()
    {
         //Runs via a 1500CC Toyota engine

    }

    public void Accelerate()
    {
         //Accelerates via an Auto gear

    }

    public void Break()
    {
         //Breaks via an hydrolic break

    }

    public void Stop()
    {
         //Stops with a key

    }

}


Looks pretty good, but, wait a minute. The Camry and the XCorolla class both seem to be having a same implementation forAccelerate() and Break(), though, these two classes implement the other three functionality Start()Run() and Stop() in different ways. So, as these two classes have a same implementation for the Accelerate() and Break() functionality, why shouldn't these be re-used?


The IVehicle interface could of-course be used in this case, but, it is not allowing to re-use the same functionality Accelerate() andBreak(). So, how about using an Abstract class?

Let us help Toyota to improve their programs a bit, by creating an abstract class Car, that contains the common functional implementation for Accelerate and Break.

abstract class Car : IVehicle
{
    public abstract void Start();
    public abstract void Run();
    public abstract void Stop();
    
    public void Accelerate()
    {
         //Accelerates via an Auto gear
    }
    public void Break()
    {
         //Breaks via an hydrolic break
    }
}

As you see, the abstract class Car contains concrete implementations of Accelerate() and Break() function (They have method definition), but, abstract implementation of Start()Run() and Stop() (They don't have method definition). Why two concrete implementations? Because, these two functions are the same for both Camry and the XCorolla classes. Why two abstract implementations? Because, these two function's concrete implementation are not same for Camry and XCorolla classes.

So now, the Camry and the XCorolla classes would be re-defined as follows:

class Camry : Car
{
     public void Start()
    {
         //Starts with a Remote control
    }
     public void Run()
    {
         //Runs via a 2000CC Toyota engine
    }
    public void Stop()
    {
         //Stops with a key, or a remote control
    }
}

class XCorolla: Car
{
     public void Start()
    {
         //Starts with a Key

    }
     public void Run()
    {
         //Runs via a 1500CC Toyota engine

    }
    public void Stop()
    {
         //Stops with a key

    }
}

This time, the Camry and the XCorolla classes don't include the definition of  Break() and Accelerate(), because, they inherit those from the abstract Car class.


To summarize, the purpose of abstract classes is not only to define abstraction between classes, but also to define concrete definition of functions which are common across the concrete implementation classes. Interfaces allow us to identify (Not implement) the functionality a particular kind of object where Abstract classes allows to both identify and implement the functionality across the objects, that increases re-usability and code manageability and allows to build better systems.

However, it doesn't mean that, all interfaces should be replaced with Abstract classes. Try to use Abstract classes wherever possible and wherever applicable, where use of Abstract classes allows you to increase code manageability and reuse.

Sunday 26 June 2016

Transaction begin, commit or rollback while inserting in multiple table if any exception occurs.

Protect void InsertRecord(object sender,EventArgs e)

string strConnection = string.Empty;
SqlConnection sqlCon;
SqlCommand sqlCommand;
SqlTransaction sqlTran = null;
DataSet ds;
Try
{
BaseHelper objBase = new BaseHelper();
strConnection = objBase.getConnectionString(companyId, “TRM”);
sqlCon = new SqlConnection();
sqlCon.ConnectionString = strConnection;
sqlCon.Open();
sqlTran = sqlCon.BeginTransaction();
#region ————First Table Insert————————
sqlCommand = new SqlCommand();
sqlCommand.CommandText = sp_test
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Connection = sqlCon;
sqlCommand.Transaction = sqlTran;
sqlCommand.Parameters.Add(“@qryno”, SqlDbType.TinyInt).Value =”123″;
string[] sSplit = sqlCommand.ExecuteScalar().ToString().Split(‘#’);
id= Convert.ToInt32(sSplit[0].ToString());
name= sSplit[1].ToString();
#endregion ————First Table Insert————————
#region ————Second Table Insert————————
sqlCommand = new SqlCommand();
sqlCommand.CommandText = “fsp_Hotel_Reservation_Ins”;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Connection = sqlCon;
sqlCommand.Transaction = sqlTran;
for(int i=0;i<5;i++)
{
sqlCommand.Parameters.Clear();
sqlCommand.Parameters.Add(“@id”, SqlDbType.BigInt).Value = Convert.ToInt32(Id)
Id = Convert.ToInt32(sqlCommand.ExecuteScalar());
}
#region ————Second Table Insert————————
sqlTran.Commit();
sMsg = “DONE#” + reservationID.ToString() + “#” + ReservationRef;
}
catch (Exception ex)
{
sqlTran.Rollback();
sMsg = “ERROR#ERROR”;
appendString(“—- In Catch:log Error —-“);
appendString(“—- Error : —-” + ex.ToString());
appendString(“—- XML : —-” + xDoc.OuterXml);
}
finally
{
sqlCon.Close();
if (strLog.Length > 0)
{
CommonLib.WriteTraceInfo(“App_Code”, “Test Class”, strLog.ToString(), companyId);
strLog.Remove(0, strLog.Length);
}
}
}

Add User Control dynamically in PlaceHolder on aspx Page from Code Behind.

————————-aspx  code——————
<asp:PlaceHolder runat=”server” ID=”placeHolder1″ />
—– ——————C# Code    —————————
protected void AddDynamicallyUserControl()
{
//<asp:PlaceHolder runat=”server” ID=”placeHolder1″ />
PlaceHolder placeHolder1 = this.Master.FindControl(“ControlPlaceHolder1”).FindControl(“placeHolder1”) as PlaceHolder;
if (placeHolder1 != null)
{
Control _Control = default(Control);
_Control = Page.LoadControl(“~/UserControl/Login.ascx”);
placeHolder1.Controls.Add(_Control);
}
else
{
//
}
}
Posted on

Get XML from DataSet and convert into html using xslt dynamuically


protected void UseXslt()
{
XmlDocument xDS = new XmlDocument();
DataSet ds = new DataSet();
// ds = // Get DataSet from  DataBase.
xDS.LoadXml(ds.GetXml());
string sType = string.Empty;
// Get Value From Node
sType = xDS.DocumentElement.SelectSingleNode(“Data/Type”).InnerText;
// Add new Node in Existing XML
XmlElement xEml = xDS.CreateElement(“BType”);
xEml.InnerText = “Hi”;
xDS.DocumentElement.SelectSingleNode(“Data”).AppendChild(xEml);
string _xsltPath = string.Empty;
_xsltPath = “~/Users/User.xslt”;
XsltArgumentList xslArg = new XsltArgumentList();
string _resultHtml = String.Empty;
_resultHtml =ConvertXMLFromXSLT(xDS.OuterXml, _xsltPath, xslArg);
UserData.InnerHtml = _resultHtml;// <div id=”UserData” runat=”server”></div>  in  aspx page
}
public static string ConvertXMLFromXSLT(string XmlName, string XSLTFileName, XsltArgumentList arg)
{
XslCompiledTransform objXSL = new XslCompiledTransform();
// XsltArgumentList args = new XsltArgumentList();
XmlDocument XmlDoc = new XmlDocument();
string convertedXML = String.Empty;
XmlDoc.LoadXml(XmlName);
objXSL.Load(XSLTFileName);
try
{
XmlWriterSettings objSettings = new XmlWriterSettings();
objSettings.ConformanceLevel = ConformanceLevel.Auto;
System.Text.StringBuilder sb = new System.Text.StringBuilder(“”);
XmlWriter objXML = XmlWriter.Create(sb, objSettings);
objXSL.Transform(XmlDoc, arg, objXML);
convertedXML = sb.ToString();
}
catch (Exception ex)
{
}
return convertedXML;
}
Posted on

Add MasterPage Dynamically from CodeBehind asp.net c#

protected void Page_PreInit(object sender, EventArgs e)
{
string masterPath = string.Empty;
string _userType = Request.QueryString[“sType”].ToString();
switch (_userType)
{
case “User”:
masterPath = “~/User/Master/”;
Page.MasterPageFile = masterPath + “UserMaster.master”;
break;
case “Admin”:
masterPath = “~/Admin/Master/”;
Page.MasterPageFile = masterPath + “AdminMaster.master”;
break;
default:
Page.MasterPageFile = masterPath + “MainMaster.master”;
break;
}
}

download html content of a page by its URL in asp.net c#.

public void GetPageHtmlBy Url()
{
// using System.Net;
WebClient webClient = new WebClient();
// Get Web Page URL that content you want to send in email.
string strUrl = “abc.aspx?id=100”;
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string PgStr = objUTF8.GetString(reqHTML);
System.Text.RegularExpressions.Regex regxmaster1 = new System.Text.RegularExpressions.Regex(“(<input type=\”submit\”)(.*?)(/>)”, System.Text.RegularExpressions.RegexOptions.Singleline);
System.Text.RegularExpressions.Match matchmaster1 = regxmaster1.Match(PgStr);
string inputype1 = matchmaster1.Groups[0].Value.Trim();
if (inputype1.Trim() != “”)
{
PgStr = PgStr.Replace(inputype1, “”);
}
// replace any value
string imgUrl=””;
PgStr = PgStr.Replace(” id=\”img1\””, ” src=\”” + imgUrl + “\”  id=\”img1\””);
// remove any text or control conditionaly
if (Request.QueryString[“flag”].ToString() == “M”)
{
PgStr = PgStr.Remove(PgStr.IndexOf(“Full Details”), 9);
}
// here you  can  use content from  other page as mail body or  display other place.
}

Open new pop up window on href click . Then prind window.

style>
@media print {
.noprint {
display: none !important;
}
</style>

<a id="lnkPrintReceipt" class="link" onclick="javascript:window.open('../../admin/Reciept.aspx?Id=216&Type=TY’,’PaymentReceipt’,’width=800,height=500,toolbar=0,scrollbars=1′)" target="_blank" style="cursor: pointer; text-decoration: none;">PMT0311</a>

<div class="btn">
<input type="submit" name="ctl01″ value="Print Receipt" onclick="javascript: window.print();" class="btn_blue no-print">
</div>

Bind some fix lenght string in GridView with Eval and Substring in asp.net.

<%#Eval(“News”).ToString().Length>=50?Eval(“News”).ToString().Substring(0,50):Eval(“News”).ToString() %>

Conditional base style in Gridview using Eval() Method.

<a href=’Receipt.aspx?Id=<%#Eval(“RecNo”) %>&TravellerId=<%#Eval(“StID”) %>’ onclick=”window.open(this.href,’targetWindow’,
‘toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=500,
height=600′);return false;”
style=’display:<%#(Eval(“RecNo”).ToString())!=”” ? “block”: “none” %>’>View Receipt</a>

Radiobutton Checked changed event in gridview.

protected void rdbdiscontinued_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rd = (RadioButton)sender;
            GridViewRow row = (GridViewRow)rd.NamingContainer;
            Label lblprodid = (Label)row.FindControl("lblproductid");
            Label lbproductname = (Label)row.FindControl("lblproductname");
            Label lbcategoryid = (Label)row.FindControl("lblcategoryid");
            Label lbunit = (Label)row.FindControl("lblunitprice");
            Label txtunitstock = (Label)row.FindControl("lblunitsinstock");
            if (rd.Checked == true)
            {
                Productsbll pbl = new Productsbll();
                Products prod = new Products();
                row.Visible = false;
                prod.Productid = Convert.ToInt32(lblprodid.Text);
                prod.ProductName = lbproductname.Text;
                prod.CategoryID = Convert.ToInt32(lbcategoryid.Text);
                prod.UnitPrice = Convert.ToInt32(lbunit.Text);
                prod.UnitsinStock = Convert.ToInt32(txtunitstock.Text);
                pbl.UpdateProduct(prod);
            }
            GetProducts();
        }

Filter Dataset without hiting database using Dataview.

DataSet ds = (DataSet)ViewState[“dsChannel”];// get your dataset
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = “ChannelId in (” + channelId + “)”; //  filter string
return  dv.table // it return  filtered row(s)  from dataset
If  you want to selcet single value from  returned datarow
string str= dv[0][“ChannelCode”].ToString()

Get DataSet from XML File in ASP.Net C#.

DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/Customers.xml"));
// You  can  use this  data Set as DataSouse  to bind Grid etc..

Important Run Commond

To Access…
Run Command
Accessibility Controls
access.cpl
Accessibility Wizard
accwiz
Add Hardware Wizard
hdwwiz.cpl
Add/Remove Programs
appwiz.cpl
Administrative Tools
control admintools
Adobe Acrobat (if installed)
acrobat
Adobe Designer (if installed)
formdesigner
Adobe Distiller (if installed)
acrodist
Adobe ImageReady (if installed)
imageready
Adobe Photoshop (if installed)
photoshop
Automatic Updates
wuaucpl.cpl
Bluetooth Transfer Wizard
fsquirt
Calculator
calc
Certificate Manager
certmgr.msc
Character Map
charmap
Check Disk Utility
chkdsk
Clipboard Viewer
clipbrd
Command Prompt
cmd
Component Services
dcomcnfg
Computer Management
compmgmt.msc
Control Panel
control
Date and Time Properties
timedate.cpl
DDE Shares
ddeshare
Device Manager
devmgmt.msc
Direct X Control Panel (if installed)*
directx.cpl
Direct X Troubleshooter
dxdiag
Disk Cleanup Utility
cleanmgr
Disk Defragment
dfrg.msc
Disk Management
diskmgmt.msc
Disk Partition Manager
diskpart
Display Properties
control desktop
Display Properties
desk.cpl
Display Properties (w/Appearance Tab Preselected)
control color
Dr. Watson System Troubleshooting Utility
drwtsn32
Driver Verifier Utility
verifier
Event Viewer
eventvwr.msc
Files and Settings Transfer Tool
migwiz
File Signature Verification Tool
sigverif
Findfast
findfast.cpl
Firefox (if installed)
firefox
Folders Properties
folders
Fonts
control fonts
Fonts Folder
fonts
Free Cell Card Game
freecell
Game Controllers
joy.cpl
Group Policy Editor (XP Prof)
gpedit.msc
Hearts Card Game
mshearts
Help and Support
helpctr
HyperTerminal
hypertrm
Iexpress Wizard
iexpress
Indexing Service
ciadv.msc
Internet Connection Wizard
icwconn1
Internet Explorer
iexplore
Internet Properties
inetcpl.cpl
Internet Setup Wizard
inetwiz
IP Configuration (Display Connection Configuration)
ipconfig /all
IP Configuration (Display DNS Cache Contents)
ipconfig /displaydns
IP Configuration (Delete DNS Cache Contents)
ipconfig /flushdns
IP Configuration (Release All Connections)
ipconfig /release
IP Configuration (Renew All Connections)
ipconfig /renew
IP Configuration (Refreshes DHCP & Re-Registers DNS)
ipconfig /registerdns
IP Configuration (Display DHCP Class ID)
ipconfig /showclassid
IP Configuration (Modifies DHCP Class ID)
ipconfig /setclassid
Java Control Panel (if installed)
jpicpl32.cpl
Java Control Panel (if installed)
javaws
Keyboard Properties
control keyboard
Local Security Settings
secpol.msc
Local Users and Groups
lusrmgr.msc
Logs You Out Of Windows
logoff
Malicious Software Removal Tool
mrt
Microsoft Access (if installed)
msaccess
Microsoft Chat
winchat
Microsoft Excel (if installed)
excel
Microsoft Frontpage (if installed)
frontpg
Microsoft Movie Maker
moviemk
Microsoft Paint
mspaint
Microsoft Powerpoint (if installed)
powerpnt
Microsoft Word (if installed)
winword
Microsoft Syncronization Tool
mobsync
Minesweeper Game
winmine
Mouse Properties
control mouse
Mouse Properties
main.cpl
Nero (if installed)
nero
Netmeeting
conf
Network Connections
control netconnections
Network Connections
ncpa.cpl
Network Setup Wizard
netsetup.cpl
Notepad
notepad
Nview Desktop Manager (if installed)
nvtuicpl.cpl
Object Packager
packager
ODBC Data Source Administrator
odbccp32.cpl
On Screen Keyboard
osk
Opens AC3 Filter (if installed)
ac3filter.cpl
Outlook Express
msimn
Paint
pbrush
Password Properties
password.cpl
Performance Monitor
perfmon.msc
Performance Monitor
perfmon
Phone and Modem Options
telephon.cpl
Phone Dialer
dialer
Pinball Game
pinball
Power Configuration
powercfg.cpl
Printers and Faxes
control printers
Printers Folder
printers
Private Character Editor
eudcedit
Quicktime (If Installed)
QuickTime.cpl
Quicktime Player (if installed)
quicktimeplayer
Real Player (if installed)
realplay
Regional Settings
intl.cpl
Registry Editor
regedit
Registry Editor
regedit32
Remote Access Phonebook
rasphone
Remote Desktop
mstsc
Removable Storage
ntmsmgr.msc
Removable Storage Operator Requests
ntmsoprq.msc
Resultant Set of Policy (XP Prof)
rsop.msc
Scanners and Cameras
sticpl.cpl
Scheduled Tasks
control schedtasks
Security Center
wscui.cpl
Services
services.msc
Shared Folders
fsmgmt.msc
Shuts Down Windows
shutdown
Sounds and Audio
mmsys.cpl
Spider Solitare Card Game
spider
SQL Client Configuration
cliconfg
System Configuration Editor
sysedit
System Configuration Utility
msconfig
System File Checker Utility (Scan Immediately)
sfc /scannow
System File Checker Utility (Scan Once At The Next Boot)
sfc /scanonce
System File Checker Utility (Scan On Every Boot)
sfc /scanboot
System File Checker Utility (Return Scan Setting To Default)
sfc /revert
System File Checker Utility (Purge File Cache)
sfc /purgecache
System File Checker Utility (Sets Cache Size to size x)
sfc /cachesize=x
System Information
msinfo32
System Properties
sysdm.cpl
Task Manager
taskmgr
TCP Tester
tcptest
Telnet Client
telnet
Tweak UI (if installed)
tweakui
User Account Management
nusrmgr.cpl
Utility Manager
utilman
Windows Address Book
wab
Windows Address Book Import Utility
wabmig
Windows Backup Utility (if installed)
ntbackup
Windows Explorer
explorer
Windows Firewall
firewall.cpl
Windows Magnifier
magnify
Windows Management Infrastructure
wmimgmt.msc
Windows Media Player
wmplayer
Windows Messenger
msmsgs
Windows Picture Import Wizard (need camera connected)
wiaacmgr
Windows System Security Tool
syskey
Windows Update Launches
wupdmgr
Windows Version (to show which version of windows)
winver
Windows XP Tour Wizard
tourstart
Wordpad
write