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)