Monday, November 25, 2013

How to disable jQuery UI tab(s)

Single tab

$( "#tabs" ).tabs( "option", "disabled", 1);

Multiple tabs

$( "#tabs" ).tabs('option','disabled', [1, 2, 3, 4]);

Saturday, November 9, 2013

An entry with the same key already exists.

Causes:
  • Multiple asp net controls with same ID
  • Mostly occurs inside ListView control 
  • Keep an eye on validator controls. Try to have different id on master and child pages.

Sunday, November 3, 2013

Change an Image while using JCrop

Initialize jCrop
var jcrop_api;
        function InitjCrop() {
            $('#id').Jcrop({  }, function () {
                jcrop_api = this;
            });
        }
To unhook jCrop
jcrop_api.destroy();
To Hook jCrop again
InitjCrop();

Wednesday, October 30, 2013

How do I cancel a Delete in MSSQL SERVER

We use instead of delete trigger's ROLLBACK TRAN to cancel a delete statement CREATE TRIGGER dbo.t__protect__locked__from__delete
ON dbo.table
instead OF DELETE
AS
  BEGIN
      SET nocount ON

      DECLARE @IsLocked BIT,
              @ID       INT

      SELECT @IsLocked = IsLocked,@ID = ID
      FROM   deleted

      IF @IsLocked = 1
        BEGIN
            RAISERROR ('Cannot delete',16,1)
            ROLLBACK TRAN
            RETURN
        END
      -- Go ahead and do the update or some other business rules here
      ELSE
        DELETE FROM table
        WHERE  ( ID = @ID )
  END
GO

Tuesday, October 29, 2013

FormView must be in insert mode to insert a new record.

Just change
<asp:LinkButton ...........CommandName="Insert">New</asp:LinkButton>
to
<asp:LinkButton .......... CommandName="New">New</asp:LinkButton>

Monday, October 28, 2013

Validating date using Range Validator asp net

Q: Why Validate date using Range Validator? 
A: All validation controls use culture specified in the web.config globalization tag. We don't need to hard code values every time we change culture. So using Range Validator as a date comparator makes things easy. To use range validator make sure to specify Type="Date" else it won't work. Choose Maximum and Minimum Values as required

<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Invalid Date" 
Type="Date" ControlToValidate="{}" MaximumValue="3000-12-12" MinimumValue="1900-12-12">
</asp:RangeValidator>

Thanks

Crystal Reports: Suppressing a object based on condition

Suppressing a object based on condition is pretty easy. Just use a Boolean field or Boolean parameter or an expression that returns Boolean value.

No if else is required.

e.g.

{?ShowPaid}
 
If it returns true object will be suppressed else no

Sunday, October 27, 2013

Count total rows of gridview with pagination asp net

For this example
GridView ID: gvStudents
SqlDataSourceID: dsApplications
Event: dsApplications_Selected
protected void dsApplications_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
   int PageIndex = gvStudents.PageIndex;
   int start = PageIndex * gvStudents.PageSize + 1;
   int end = Math.Min(start + gvStudents.PageSize - 1, e.AffectedRows);
   navi.InnerHtml = string.Format("Showing record {0} - {1} of {2}", start, end, e.AffectedRows);
}

Friday, October 25, 2013

Hide InsertItem While Editing in listview asp net c#

If you want to hide InsertItem while editing just use these three events

protected void lv_ItemEditing(object sender, ListViewEditEventArgs e)
{
     ListView lvSender = (ListView)sender;
     lvSender.InsertItemPosition = InsertItemPosition.None;
}
 
protected void lv_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
{
      ListView lvSender = (ListView)sender;
      lvSender.InsertItemPosition = InsertItemPosition.FirstItem;
}
 
protected void lv_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
     ListView lvSender = (ListView)sender;
     lvSender.InsertItemPosition = InsertItemPosition.FirstItem;
}
and then append this to list view
OnItemCanceling="lv_ItemCanceling" OnItemUpdated="lv_ItemUpdated" OnItemEditing="lv_ItemEditing"
Hope this helps

Crystal Reports: Missing Parameter Values

Steps to solve the problem Crystal Missing Parameter Values
  • Make sure SetParameterValues are not empty or null
  • Use ReportDocument.SetParameterValues after loading main report and most importantly subreports
  • If you use setparametervalues between load report and subreport this error will occur
    • Settings subreports  nullifies previous set parameter values

Tuesday, October 15, 2013

Sending SMTP mail using phpmailer

<?phprequire_once ('../class.phpmailer.php');
// include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch$mail->IsSMTP(); // telling the class to use SMTPtry { $mail->Host "mail.yourdomain.com"// SMTP server $mail->SMTPDebug 2// enables SMTP debug information (for testing) $mail->SMTPAuth true// enable SMTP authentication $mail->SMTPSecure "tls"// sets the prefix to the servier $mail->Host "smtp.gmail.com"// sets GMAIL as the SMTP server $mail->Port 587// set the SMTP port for the GMAIL server $mail->Username "yourusername@gmail.com"// GMAIL username $mail->Password "yourpassword"// GMAIL password $mail->AddReplyTo('name@yourdomain.com''First Last'); $mail->AddAddress('whoto@otherdomain.com''John Doe'); $mail->SetFrom('name@yourdomain.com''First Last'); $mail->AddReplyTo('name@yourdomain.com''First Last'); $mail->Subject 'PHPMailer Test Subject via mail(), advanced'; $mail->AltBody 'To view the message, please use an HTML compatible email viewer!'// optional - MsgHTML will create an alternate automatically $mail->MsgHTML(file_get_contents('contents.html')); $mail->AddAttachment('images/phpmailer.gif'); // attachment $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment $mail->Send(); echo "Message Sent OK<p></p>\n"; }

catch(
phpmailerException $e) { echo $e->errorMessage(); //Pretty error messages from PHPMailer }

catch(
Exception $e) { echo $e->getMessage(); //Boring error messages from anything else! }

PHPMailer SMTP Error: Could not authenticate using gmail as smtp server

PHPMailer SMTP Error: Could not authenticate using gmail as smtp server
Causes
  1. invalid username
    1. try username@gmail.com instead of username
  2. invalid password
  3. invalid secure option
    1. use ssl, tls not SSL, TLS
  4. invalid port 
    1. use port 587 or 465

Wednesday, October 9, 2013

Regenerate / Create new SessionId using SessionManager asp net c#

SessionIDManager manager = new SessionIDManager();
string newSID = manager.CreateSessionID(Context);
bool redirected, cookieAdded;
manager.SaveSessionID(Context, newSID, out redirected, out cookieAdded);

Tuesday, October 8, 2013

Inserting text after cursor position in text areа

$.fn.extend({
                   insertAtCaret: function (myValue) {
                        if (!this.selectionStart)
                            thi = $(this).get(0);
                        if (thi.selectionStart || thi.selectionStart == '0') {
                            var startPos = thi.selectionStart;
                            var endPos = thi.selectionEnd;
                            var scrollTop = thi.scrollTop;
                            thi.value = thi.value.substring(0, startPos) + myValue + thi.value.substring(endPos, thi.value.length);
                            thi.focus();
                            thi.selectionStart = startPos + myValue.length;
                            thi.selectionEnd = startPos + myValue.length;
                            thi.scrollTop = scrollTop;
                        } else {
                            thi.value += myValue;
                            thi.focus();
                        }
                    }
                })

Convert jQuery object to DOM object

jQuery Object
$('textarea')
example of setting a value
$('textarea').val("Hi");
DOM object
$('textarea').get(0)
example of setting a value
$('textarea').get(0).value = "Hi";

Monday, October 7, 2013

Default export name in the crystal report viewer

Solution 1:
Change ID of Crystal Report Viewer to whatever you want the filename to be.

Solution 2:
Set ID of Crystal Report Viewer to whatever you want the filename to be. like

CrystalReportViewer1.ID = "File name without Spaces and any weird characters";

DateTime to Text / String in Crystal Report

ToText({datefield},"[DATE FORMAT]")
DATE FORMAT EXAMPLES
ExampleOutput
dd-MMM-yyyy07-Oct-2013
dd/MM/yyyy07/10/2013

Removing / dropping / deleting a column from all tables in ms sql server

exec sp_msforeachtable 'alter table ? drop column COL_NAME'

Saturday, October 5, 2013

Web Client :: Asynchronous operations are not allowed in this context. asp net

Add the Async="true" parameter to the @Page directive. like this

<%@ Page Async="true" AsyncTimeout="3000" ......

How to call API URL in asp.net c#

string url = "{url}"
string param = "name value pair data";
System.Net.WebClient webClient = new System.Net.WebClient();
string encoding = "application/x-www-form-urlencoded";
webClient.Headers[System.Net.HttpRequestHeader.ContentType] = encoding;
string res = webClient.UploadString(url, param);

How do I return a value to a sqldatareader if value is null? asp net c#

int CountryId;
SqlDataReader reader = ...........
 
if (reader.HasRows)
{
 reader.Read();
 CountryId = reader.GetInt16(reader.GetOrdinal("CountryId"));
 
But if CountryId is null it will throw an exception so use safe method

CountryId = !string.IsNullOrWhiteSpace(reader["CountryId"].ToString()) ? 
Convert.ToInt32(reader["CountryId"]) : -1; 

That is it

Tuesday, October 1, 2013

Why unknown file types are not served by IIS

Here is the command:
%windir%\system32\inetsrv\appcmd set config /section:staticContent /+"[fileExtension='.3gp',mimeType='video/3gpp']"
And while we are at it. You might run into the same problem with MP4 files. Here is the appcmd for it:
%windir%\system32\inetsrv\appcmd set config /section:staticContent /+"[fileExtension='.mp4',mimeType='video/mpeg']"

Get Week Day No and Name in Crystal Report

First Get WeekDay No using this function

WeekDay ({DateGoesHere}, firstDayOfWeek) 
date(DateTime): Any valid date, 
firstDayOfWeek(int): Possible Values[crMonday, crTuesday, crWednesday, crThursday, crFirday, crSaturday, crSunday]: Default crSunday
Then use
WeekDayName(WeekDay ({DateGoesHere}, firstDayOfWeek), false, firstDayOfWeek)

Monday, September 30, 2013

Adding a column to all user tables in ms sql server

There is an undocumented but well known stored procedure sp_msforeachtable:
exec sp_msforeachtable 'alter table ? add {colname} {dataType} {null|not null} ....';

Friday, September 27, 2013

Remove totals from crystal report cross tab

In the top-left corner of the Cross-Tab there is a blank cell - right click inside that cell and select Cross-Tab Expert from the shortcut menu.


On the third tab, Customize Style, there are check boxes where you can suppress subtotals and grand totals.

Variable persistence on postback asp net

An ASP.NET page class file is destroyed after it is served to the client. The most chosen method for preserving variables in ASP.NET from one page load to the next is to store them in
  • ViewState
    • Small data for current page only
  • Session
    • Small or large data for across the web site or app
  • Hidden Input 
    • Small data for current page only
  • Cookies
    • Small data for long time across the website or app
  • Cache 
    • Small or large data for across the website or app

Saturday, September 21, 2013

How to change the .htaccess file name?


To use a different name from the the default .htaccess use the AccessFileName directive in httpd.conf file.
AccessFileName yourFileName
All you need to do is to reload Apache and the new setting will take effect.

TopHost Hostgator GoDaddy .htaccess Settings

The top web comes with mod_rewrite enabled. To use it, create a. htaccess file with the appropriate directives. 

Remember to always insert the Directive: 
RewriteBase / 

where / and 'the path of the. htaccess file, so if the. htaccess file is located in the subfolder demo must' be: 
RewriteBase /demo

Wednesday, September 11, 2013

How to hide asp net DataPager when there is only one page

When you use DataPager with ListView and there is only one page of data you still see the pager. So if you don't like the pager like me you can use below piece of code to hide it.

//Data Pager Outside ListView
        protected void lView_DataBound(object sender, EventArgs e)
        {
            dPager1.Visible = (dPager1.PageSize < dPager1.TotalRowCount);
        }
 
        //Data Pager Inside ListView
        protected void lView_DataBound(object sender, EventArgs e)
        {
            DataPager dPager = (DataPager)lView.FindControl("dPager1");
            dPager.Visible = (dPager.PageSize < dPager.TotalRowCount);
        }

Tuesday, September 10, 2013

How to display original quality image in Crystal Reports

Step 1:
Open any crystal report
Step 2:
Go to Menu->Crystal Report->Design->Default Settings
Step 3:
Go to Reporting Tab and make sure "Retain Original Image Color Depth" is checked

Note: Try using images with no transpareny for good quality.

Sunday, September 8, 2013

What is the difference between Public, Private, Protected And Internal

Anywhere Same  class Derived Classes Same Assembly Derived Classes in
another assembly
Public




Private




Protected



Internal




Protected
internal



Saturday, September 7, 2013

How to reset / change user password programmatically using asp net membership

MembershipUser user = Membership.GetUser({UserId});
user.ChangePassword(user.ResetPassword(), {NewPassword});

How to restrict get; setter; to get only inside c# asp net classes

Lets say you have a get, set property inside a class say IP
public String IP { get; }
 
When I specify get only I wont be able to set the property even inside the class itself. e.g
this.IP = "127.0.0.1";
Property or indexer 'IP' cannot be assigned to -- it is readonly 
Solution, just type private keyword with set property like this
public String IP { getprivate set; }
All done

Wednesday, September 4, 2013

How to get first and last day of month asp net c#

First day of month
    public static DateTime GetFirstDayOfMonth(DateTime dt)
    {
        return new DateTime(dt.Year, dt.Month, 1);
    }
Last day of month
    public static DateTime GetLastDayOfMonth(DateTime dt)
    {
        return new DateTime(dt.Year, dt.Month, 1).AddMonths(1).AddDays(-1);
    }

Tuesday, September 3, 2013

Search Stored Procedure for Column Name in MS SQL SERVER

SELECT DISTINCT OBJECT_NAME(OBJECT_ID),object_definition(OBJECT_ID)FROM sys.ProceduresWHERE object_definition(OBJECT_ID) LIKE '%' + '{COL_NAME}' +'%'

SAP Crystal Reports for visual studio 2010 and 2012 and 2013

Support Packs, Fixed Issues and Distribution File downloads

Fixes for each Support Pack are prioritized and released on or about end of each yearly quarter. All support packs are full builds of Crystal Reports for Visual Studio 2010/2012, thus it is not necessary to update incrementally. The most recent Support Pack in the below table is listed first.
To keep current and up to date with new releases as well as KBAs and more follow us on Twitter
Update: All Service Packs are cumulative so we are removing the links to previous patches and will be keeping 3 or 4 still active. Links still work if you have them. For installing and starting at the RTM build and progressing to the latest SP is not required.

Please note: To integrate "SAP Crystal Reports, developer version for Microsoft Visual Studio" into VS 2010 or 2012 (SP 7 and higher) or VS 2013 (SP 9 or higher) or VS 2015 RC (SP14) - VS 2015 (fully - SP 15), you must run the Install Executable. Running the MSI will not fully integrate Crystal Reports into VS. MSI files by definition are for runtime distribution only.
By default Windows 10 does not install the 3.5 framework, CR for VS still needs it. Select it by "Turn Windows feature on or off" and choose both options.

Note 2: SAP Crystal Reports, Developer Version for Visual Studio .NET does NOT support Express Editions of any version of Visual Studio .NET. VS.

New In SP16 Release
  1. Support for Edge browser on Win 10.
  2. Support for Safari 9 on Mac OS 10.11.
  3. Addressed several Incidents. 
    4. Support for HANA SP11

Install ExecutableFixed IssuesMSI 32 BitMSI 64 BitMSM
32 Bit
ClickOnce
32/64
ClickOnce
"Homesite"
WEB XML Deployment
Support Pack 16
(v.13.0.16.1954
SP16 Fixed Issues32bit.msi64bit.msi13_0_16.msnClickonce32/64clickonce32
clickonce64
crdbxml16.msi
Support Pack 15
(v.13.0.15.1840
SP15 Fixed Issues32bit.msi64bit.msi13_0_15.msnClickonce32/64clickonce32
clickonce64
crdbxml15.msi
Support Pack 14
(v.13.0.14.1720)
SP14 Fixed Issues32bit.msi64bit.msi13_0_14.msnclickonce32/64clickonce32
clickonce64
crdbxml14.msi
Support Pack 13
(v.13.0.13.1597)
SP13 Fixed Issues32bit.msi64bit.msi13_0_13.msnclickonce32/64clickonce32
clickonce64
crdbxml13.msi
Support Pack 12 (v.13.0.12.1494)SP12 Fixed Issues Wiki32bit.msi64bit.msi13_0_12.msnclickonce32/64clickonce32
clickonce64
crdbxml12.msi
RTM
(v. 13.0.0.x)
Release Notes
Installation Guide
32bit.msi64bit.msi13_0.msmclickonce32/64clickonce32
clickonce64
N/A
( previous Fixed Issues links are in the current links )

WARNING: Please refer to Knowledge Base article 2007224 for more info on configuring WEB Applications in Visual Studio 2013.
WARNING 2 - SP 11 had Regression issues, please use the latest SP now for all updates
SP 8 ClickOnce Note: There is a minor issue in the Product.xml file for ClickOnce Deployment package.
See Kbase 1957502 or manually modify the file to update the version:
<BypassIf Property="CRRuntime64Version" Compare="VersionGreaterThanOrEqualTo"  Value="13.0.8"/>
Only affects the Developers PC.
Note: Manual deployment of crdb_xml drivers requires manually installing and deploying JRE/JDK
1871962 - How To manually deploy Service Pack 6, and above, crdb_XML data source driver for Crystal Reports Developer for Visual Studio
Note: Clickonce32/64 is managed by the xml file for which one is installed.
1534388 - CRVS2010 - Creating Click Once deployment
Note: Click Once "Homesite" is to tell your installer to go here for the runtime.

Wednesday, August 28, 2013

How to change Oc-admin folder in Osclass?

First Change the name of oc-admin folder. 
Then change the following variable
 $path .= "oc-admin/"; to your desired name in osc_admin_base_path and osc_admin_base_url functions. But it should be same as the name of your folder that you changed. 
osc_admin_base_path and osc_admin_base_url both defined on oc-includes/osclass/helpers/hDefines.phpThat's the best and easiest way to do it.

How to read a file into byte array in asp net C# or VB?

Just use
System.IO.File.ReadAllBytes(filename);

Tuesday, August 27, 2013

How to check if column was modified using trigger in sql server

CREATE TRIGGER dbo.haschanged --Any Trigger name
ON [table]
after UPDATE
AS
  BEGIN
      SET nocount ON;

      DECLARE @Old VARCHAR(100),
              @New VARCHAR(100)

      SELECT @New = i.[col]
      FROM   inserted AS i

      SELECT @Old = d.[col]
      FROM   deleted AS d

      IF @New <> @Old
        BEGIN
            --Field was changed
            
        END
      ELSE
        BEGIN
            --Field was not changed
           
        END
  END 

OR
CREATE TRIGGER dbo.haschanged --Any Trigger name
ON [table]
after UPDATE
AS
  BEGIN
      IF UPDATE (col)
        BEGIN
            --Field was changed
            
        END
      ELSE
        BEGIN
            --Field was not changed
           
        END
  END 

Insert / Update image into SQL Server database using query (not front end application)

Using Insert

INSERT INTO [table]
            (COLUMN)
SELECT *
FROM   OPENROWSET(BULK N'Path to file', single_blob) AS [File] 


Using Update

UPDATE [table]
SET    [column] = (SELECT *
                   FROM   OPENROWSET(BULK N'Path to file', single_blob) AS
                          [File])
--Conditions if any

Monday, August 26, 2013

Hide custom errors asp net

<configuration>
    .......
    <system.web> 
        ......
        <customErrors mode="Off"/>
    </system.web>
</configuration>
 
Note: "mode values are case sensitive" 

jQuery how to check html input checkbox state

$("input[type=checkbox]").change(function () {
     var isChecked = this.checked;
     if (isChecked) {
          //rest goes here
     }
});

How to check if a string is null or empty (length 0) sql server

First convert empty value to null using "nullif" then use "isnull" to switch
SELECT Isnull(NULLIF(string1, ''), string2) AS String .......

Sunday, August 25, 2013

How to Install Softaculous on VPS or Dedicated Server with cPanel/WHM?

1. cd /usr/local/cpanel/whostmgr/docroot/cgi
2. wget -N http://www.softaculous.com/ins/addon_softaculous.php 
3. chmod  755 addon_softaculous.php 
4. /usr/local/cpanel/3rdparty/bin/php addon_softaculous.php

How to limit export formats in crystal reports


CrystalReportViewer.AllowedExportFormats = 
(int)CrystalDecisions.Shared.ViewerExportFormats.PdfFormat

Wednesday, August 21, 2013

How to scan a website for bugs using backtrack

http://www.hackforsecurity.net/2013/07/how-to-scan-website-for-bugs-using_14.html

CSS 3 Gradient Editor

Color Zilla Gradient Editor
http://colorzilla.com/gradient-editor/

Compare files online

Diff Now
http://www.diffnow.com/

Replace / Remove a newline or carriage return in T SQL

REPLACE({String}, CHAR(13)+CHAR(10), '')
Source:http://stackoverflow.com/questions/951518/replace-a-newline-in-tsql

Get size of all tables in database sql server

SELECT s.name AS SchemaName
 , t.NAME AS TableName
 , p.rows AS RowCounts
 , FORMAT(SUM(a.total_pages) * 8 / 1024.0, 'N2') AS TotalSpaceMB
 , FORMAT(SUM(a.used_pages) * 8/ 1024.0, 'N2') AS UsedSpaceMB
 , FORMAT((SUM(a.total_pages) - SUM(a.used_pages)) * 8 / 1024.0, 'N2') AS UnusedSpaceMB
FROM sys.tables t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID
 AND i.index_id = p.index_id
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
WHERE t.NAME NOT LIKE 'dt%'
 AND t.is_ms_shipped = 0
 AND i.OBJECT_ID > 255
GROUP BY s.name
 , t.Name
 , p.Rows
ORDER BY p.Rows DESC