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