ASP.NET Button Click on enter keypress with Javascript and Telerik radcombobox

by pencilvac 4/24/2012 5:18:00 AM

In most modern web browsers if you have focus in a text box and press the enter key it will submit your form for you. I came across a situation where I wanted my aspx page to postback after a user makes a selection in a telerik radcombobox and then presses the enter key. Normally this does not happen automatically like a regular text box so I need a solution:

SOLUTION: In my radcombobox I used the client side event OnClientKeyPressing:

<telerik:RadComboBox OnClientKeyPressing="CheckPressEnterKey" ID="rcbCounterParties"  runat="server"></telerik:RadComboBox>

This client side event is wired up to the javascript function specified which accepts two arguments sender and args, as is seen below:You can access which key the user pressed in the args argument. The enter key has a keyCode of 13 so with a simple if statement we can test the key, if it is indeed the enter key then we can manually click the button we want. Its that easy.


                function CheckPressEnterKey(sender, args) {

                    if (args._domEvent.keyCode == 13) {
                        document.getElementById('<%=btnLoad.ClientID  %>').click();
                    }
                }

Note: You will obviously need to put the javascript function within a telerik radcodeblock in order access the buttons client ID as shown.

Tags:

.NET | ASP.NET Enterprise Library | JavaScript | Telerik

Current username in CSharp

by ebarcza 4/21/2012 9:39:00 AM

If you need to get the username and domain of the logged-in user in your .Net application, you can access it very easily. First, include the System.Security.Princial namespace at the top of your class file. then call the getCurrent() method against WindowsIdentity, and reference it's Name property :

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Xml;
using System.Security.Principal;  // <--
--

this.nametext = WindowsIdentity.GetCurrent().Name;

   If you want to retrieve just the username without the domain portion split it on '\\'
nameOnly = WindowsIdentity.GetCurrent().Name.Split('\\')[1];

 

Tags:

C# Converting integer to binary

by ebarcza 4/19/2012 11:49:00 AM

Ever wonder how to convert an integer to binary in C#

 

string binValue = Convert.ToString(69, 2);
int intValue = Convert.ToInt32("1000101", 2);
 
System.Diagnostics.Debug.WriteLine("bin: " + binValue.ToString());
System.Diagnostics.Debug.WriteLine("int: " + intValue.ToString());
--------------------------------------------------------------------------------

 

Returns: bin: 1000101
int: 69

Tags:

Telerik Rad Loading Panel Not Working or Showing with User Controls

by pencilvac 4/19/2012 6:18:00 AM

I came across an issue with an aspx page containing a user control which had several parts of each ajaxified. We needed to ajaxifiy a number of tasks for our users which also needed telerik content loading panels so the user knew something was happening. The RadAjaxManager is located inside the aspx page as so:

         <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <ClientEvents OnRequestStart="onRequestStart" />
                <AjaxSettings>
                    <telerik:AjaxSetting AjaxControlID="rgDeals">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="rgDeals" LoadingPanelID="lpComponents" />
                            <telerik:AjaxUpdatedControl ControlID="lblRecords" />
                        </UpdatedControls>
                     </telerik:AjaxSetting>
                     <telerik:AjaxSetting AjaxControlID="btnRetrieve">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="rgDeals" LoadingPanelID="lpComponents" />
                            <telerik:AjaxUpdatedControl ControlID="lblRecords" />
                            <telerik:AjaxUpdatedControl ControlID="ucPipelineClose" LoadingPanelID="lpComponents" />
                        </UpdatedControls>
                     </telerik:AjaxSetting>    
                     <telerik:AjaxSetting AjaxControlID="ucPipelineClose">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="rgPipelineClose"
LoadingPanelID="lpPipelineClose" />
                        </UpdatedControls> 
                    </telerik:AjaxSetting>

                </AjaxSettings>
            </telerik:RadAjaxManager>

The bolded AjaxSetting is to Ajaxify the user control within the aspx page. The control ID is obviously ucPipelineClose and the updated control is a radgrid within the control. After many efforts I could not get the loading panel to appear over the radgrid as was expected when changes were made or ajaxified to the user control. Trying to change the control ID and updated controls made no difference as well.

THE SOLUTION: It seemed that the ajax manager was unable to locate exactly which controls were being updated and where exactly to put the loading panel correctly. The solution I came up with was to use a RadAjaxManagerProxy inside of the control to specify the controls to ajaxify, update, and show loading panel for. I set the control ID to the button click that is to be ajaxified, with the radgrid as the updated control and it worked beautifully.

   <telerik:RadAjaxManagerProxy ID="RadAjaxManagerProxy1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="btnSavePipelineClose">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="rgPipelineClose" LoadingPanelID="lpPipelineClose" />
                    <telerik:AjaxUpdatedControl ControlID="rgDeals" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManagerProxy>

Tags:

.NET | ASP.NET AJAX | ASP.NET Enterprise Library | Telerik

How to Check DBNull in C# ASP.NET

by rbellantoni 4/18/2012 5:01:00 AM

Here is a code sample of how to check for DBNull and null values in C# in ASP.NET. 

if (item.OwnerTableView.DataKeyValues[item.ItemIndex]["ContactID"] == null || item.OwnerTableView.DataKeyValues[item.ItemIndex]["ContactID"] == DBNull.Value)

{

}

Tags:

Access is denied when attaching a database

by ebarcza 4/12/2012 11:32:00 AM

If you get an Access is Denied error when attempting to attach an MDF file, just start SQL Management Studio as an administrator and try again.

BOOM - database attached!

Solved the issue for me!

Tags:

SQL SERVER

SQL Server validating overlapping dates, date ranges

by pencilvac 4/11/2012 5:55:00 AM

When saving records to your database you may find that you cannot allow users to save multiple similar records with overlapping date ranges. The way I went about doing this was to check for the overlap in a SQL stored procedure in SQL server.

ALTER PROCEDURE [dbo].[UpsertGroupFieldValues]
    @GroupFieldValueID int = -1,
    @TargetEntityID int,
    @TargetPKID int,
    @PKID int,
    @EntityID int,
    @GroupFieldID int,
    @StartDate DateTime,
    @EndDate DateTime,
    @UserID int,
    @GroupValueIDReturned int OUTPUT

Out of all of these parameters If these parameters match a record that is already in the database, but without overlapping dates then we are good to save it. If however, the fields do match a record already in the database WITH overlapping dates, then we cannot save the record and we need to alert the user with an error.

To check for overlap I used an IF statement with a NOT EXISTS:

                //Check if there is a similar record (matching fields) with overlapping dates.//

                IF NOT EXISTS(select * from GroupFieldValues
                            WHERE TargetEntityID = @TargetEntityID
                            AND TargetPKID = @TargetPKID
                            AND PKID = @PKID
                            AND EntityID = @EntityID
                            AND GroupFieldID = @GroupFieldID
                            AND (
                                    (@StartDate BETWEEN StartDate AND EndDate)
                                    OR (@EndDate BETWEEN StartDate AND EndDate)
                                    OR(@StartDate <= StartDate AND @EndDate >= EndDate)
                                )


                   )                           

    --Basically we have a similar record. If we do have a similar record lets see if their dates overlap. If the parameter startdate is between the records start and end then it must be overlapping. If the parameter endDate is between the records start and end then it has to be overlapping. Otherwise the only other situation I can think of is if the parameter startdate is before the records startdate and the parameter @EndDate is after the records EndDate which means overlap. If this does not exist then we can go ahead and save the record.


                         
                BEGIN
                           YOUR INSERT STATEMENT
                END
                If it does exist ( an overlap) then we raise an error.
                ELSE
                    BEGIN
                        RAISERROR('Your new grouping was not saved because a similar group already exists within the same date range.',18,1)
                        --Print'Date Confliction'
                    END

ANOTHER TOPIC OF INTEREST: If you are doing an upsert stored procedure aka you are either inserting a new record or updating an already exisitng record with the same SPROC you will have to do a separate Date overlap test. Think of this situation: Your user goes into edit mode of a record in the front end of your application or website. The user changes the end date value to be November instead of October. When you check for overlap with the process above, the check will fail because there is a record with overlapping date ranges and your parameters (The record itself you are trying to update!). A way to get by this is performing separate checks based on whether you are trying to update or insert. Example:

 

IF @GroupFieldValueID = -1 --(our primary key) aka you are trying to insert a new record since its -1 (otherwise this will be the ID of the record you want to update)
    BEGIN --run our check for the new record
                IF NOT EXISTS(select * from GroupFieldValues
                            WHERE TargetEntityID = @TargetEntityID
                            AND TargetPKID = @TargetPKID --The company
                            AND PKID = @PKID --specific Value of contract, Location, Pipeline, Pricing Area from Drop downs.
                            AND EntityID = @EntityID --Entity were grouping on IE Pipeline or Contract
                            AND GroupFieldID = @GroupFieldID
                            AND (
                                    (@StartDate BETWEEN StartDate AND EndDate)
                                    OR (@EndDate BETWEEN StartDate AND EndDate)
                                    OR(@StartDate <= StartDate AND @EndDate >= EndDate)
                                )
                           
                            )   
                BEGIN
                        --PRINT'Start if no date confliction'

                               YOUR INSERT STATEMENT
                       
                END
               
                ELSE
                    BEGIN
                        RAISERROR('Your new grouping was not saved because a similar group already exists within the same date range.',18,1)
                        --Print'Date Confliction'
                    END
                   
                   
    END   
    ELSE--if @GroupFieldValueID != -1 meaning we are trying to update a record
        BEGIN --run a slightly different check where we specify that we are looking for an overlapping record that is NOT this record (AND GroupFieldValueID != @GroupFieldValueID)
            IF NOT EXISTS(select * from GroupFieldValues
                            WHERE TargetEntityID = @TargetEntityID
                            AND TargetPKID = @TargetPKID --The company
                            AND PKID = @PKID --specific Value of contract, Location, Pipeline, Pricing Area from Drop downs.
                            AND EntityID = @EntityID --Entity were grouping on IE Pipeline or Contract
                            AND GroupFieldID = @GroupFieldID
                            AND (
                                    (@StartDate BETWEEN StartDate AND EndDate)
                                    OR (@EndDate BETWEEN StartDate AND EndDate)
                                    OR(@StartDate <= StartDate AND @EndDate >= EndDate)
                                )
                            AND GroupFieldValueID != @GroupFieldValueID
            )
                BEGIN
                      YOUR UPDATE STATEMENT
                END
            ELSE
                BEGIN
                    RAISERROR('Your Group was not updated because there is another group with overlapping date ranges. ',18,1)
                END
        END   
END

 

BOOOM no more conflicting date ranges.

List of Log4Net Conversion patters

by ebarcza 4/10/2012 12:00:00 PM

The recognized conversion pattern names are:

Conversion Pattern Name Effect
a Equivalent to appdomain
appdomain Used to output the friendly name of the AppDomain where the logging event was generated.
aspnet-cache

Used to output all cache items in the case of %aspnet-cache or just one named item if used as %aspnet-cache{key}

This pattern is not available for Compact Framework or Client Profile assemblies.

aspnet-context

Used to output all context items in the case of %aspnet-context or just one named item if used as %aspnet-context{key}

This pattern is not available for Compact Framework or Client Profile assemblies.

aspnet-request

Used to output all request parameters in the case of %aspnet-request or just one named param if used as %aspnet-request{key}

This pattern is not available for Compact Framework or Client Profile assemblies.

aspnet-session

Used to output all session items in the case of %aspnet-session or just one named item if used as %aspnet-session{key}

This pattern is not available for Compact Framework or Client Profile assemblies.

c Equivalent to logger
C Equivalent to type
class Equivalent to type
d Equivalent to date
date

Used to output the date of the logging event in the local time zone. To output the date in universal time use the %utcdate pattern. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %date{HH:mm:ss,fff} or %date{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is given then ISO8601 format is assumed (Iso8601DateFormatter).

The date format specifier admits the same syntax as the time pattern string of the ToString.

For better results it is recommended to use the log4net date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying AbsoluteTimeDateFormatter, DateTimeDateFormatter and respectively Iso8601DateFormatter. For example, %date{ISO8601} or %date{ABSOLUTE}.

These dedicated date formatters perform significantly better than ToString.

exception

Used to output the exception passed in with the log message.

If an exception object is stored in the logging event it will be rendered into the pattern output with a trailing newline. If there is no exception then nothing will be output and no trailing newline will be appended. It is typical to put a newline before the exception and to have the exception as the last data in the pattern.

F Equivalent to file
file

Used to output the file name where the logging request was issued.

WARNING Generating caller location information is extremely slow. Its use should be avoided unless execution speed is not an issue.

See the note below on the availability of caller location information.

identity

Used to output the user name for the currently active user (Principal.Identity.Name).

WARNING Generating caller information is extremely slow. Its use should be avoided unless execution speed is not an issue.

l Equivalent to location
L Equivalent to line
location

Used to output location information of the caller which generated the logging event.

The location information depends on the CLI implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses.

The location information can be very useful. However, its generation is extremely slow. Its use should be avoided unless execution speed is not an issue.

See the note below on the availability of caller location information.

level

Used to output the level of the logging event.

line

Used to output the line number from where the logging request was issued.

WARNING Generating caller location information is extremely slow. Its use should be avoided unless execution speed is not an issue.

See the note below on the availability of caller location information.

logger

Used to output the logger of the logging event. The logger conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the logger name will be printed. By default the logger name is printed in full.

For example, for the logger name "a.b.c" the pattern %logger{2} will output "b.c".

m Equivalent to message
M Equivalent to method
message

Used to output the application supplied message associated with the logging event.

mdc

The MDC (old name for the ThreadContext.Properties) is now part of the combined event properties. This pattern is supported for compatibility but is equivalent to property.

method

Used to output the method name where the logging request was issued.

WARNING Generating caller location information is extremely slow. Its use should be avoided unless execution speed is not an issue.

See the note below on the availability of caller location information.

n Equivalent to newline
newline

Outputs the platform dependent line separator character or characters.

This conversion pattern offers the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator.

ndc

Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.

p Equivalent to level
P Equivalent to property
properties Equivalent to property
property

Used to output the an event specific property. The key to lookup must be specified within braces and directly following the pattern specifier, e.g. %property{user} would include the value from the property that is keyed by the string 'user'. Each property value that is to be included in the log must be specified separately. Properties are added to events by loggers or appenders. By default the log4net:HostName property is set to the name of machine on which the event was originally logged.

If no key is specified, e.g. %property then all the keys and their values are printed in a comma separated list.

The properties of an event are combined from a number of different contexts. These are listed below in the order in which they are searched.

the event properties
The event has Properties that can be set. These properties are specific to this event only.
the thread properties
The Properties that are set on the current thread. These properties are shared by all events logged on this thread.
the global properties
The Properties that are set globally. These properties are shared by all the threads in the AppDomain.
r Equivalent to timestamp
stacktrace

Used to output the stack trace of the logging event The stack trace level specifier may be enclosed between braces. For example, %stacktrace{level}. If no stack trace level specifier is given then 1 is assumed

Output uses the format: type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1

This pattern is not available for Compact Framework assemblies.

stacktracedetail

Used to output the stack trace of the logging event The stack trace level specifier may be enclosed between braces. For example, %stacktracedetail{level}. If no stack trace level specifier is given then 1 is assumed

Output uses the format: type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...)

This pattern is not available for Compact Framework assemblies.

t Equivalent to thread
timestamp

Used to output the number of milliseconds elapsed since the start of the application until the creation of the logging event.

thread

Used to output the name of the thread that generated the logging event. Uses the thread number if no name is available.

type

Used to output the fully qualified type name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fully qualified form.

For example, for the class name "log4net.Layout.PatternLayout", the pattern %type{1} will output "PatternLayout".

WARNING Generating the caller class information is slow. Thus, its use should be avoided unless execution speed is not an issue.

See the note below on the availability of caller location information.

u Equivalent to identity
username

Used to output the WindowsIdentity for the currently active user.

WARNING Generating caller WindowsIdentity information is extremely slow. Its use should be avoided unless execution speed is not an issue.

utcdate

Used to output the date of the logging event in universal time. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %utcdate{HH:mm:ss,fff} or %utcdate{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is given then ISO8601 format is assumed (Iso8601DateFormatter).

The date format specifier admits the same syntax as the time pattern string of the ToString.

For better results it is recommended to use the log4net date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying AbsoluteTimeDateFormatter, DateTimeDateFormatter and respectively Iso8601DateFormatter. For example, %utcdate{ISO8601} or %utcdate{ABSOLUTE}.

These dedicated date formatters perform significantly better than ToString.

w Equivalent to username
x Equivalent to ndc
X Equivalent to mdc
%

The sequence %% outputs a single percent sign.

The single letter patterns are deprecated in favor of the longer more descriptive pattern names.

Tags:

Using multiple appenders in Log4Net

by ebarcza 4/6/2012 9:03:00 AM

This is an example of a log4Net winforms implementation that will log to both a database and a file. A little redundancy will never hurt@!

 <log4net debug="true">
    
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1"/>
 
      <connectionType  value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
 
      <connectionString  value="Data Source=.\SQLEXPRESS;AttachDbFilename='C:\Data\Logging.mdf';
Integrated Security=True;User Instance=True"/>
 
      <commandText value="INSERT INTO Log4Net ([Date], [Thread], [Level], [Logger], [Message],
                   [Exception]) VALUES 
                   (@log_date, @thread, @log_level, @logger, @message, @exception)"/>
 
      <parameter>
        <parameterName value="@log_date"/>
        <dbType value="DateTime"/>
        <layout type="log4net.Layout.RawTimeStampLayout"/>
      </parameter>
 
      <parameter>
        <parameterName value="@thread"/>
        <dbType value="String"/>
        <size value="255"/>
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%thread ip=%property{ip}"/>
        </layout>
      </parameter>
 
      <parameter>
        <parameterName value="@log_level"/>
        <dbType value="String"/>
        <size value="50"/>
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level"/>
        </layout>
      </parameter>
 
      <parameter>
        <parameterName value="@logger"/>
        <dbType value="String"/>
        <size value="255"/>
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger"/>
        </layout>
      </parameter>
 
      <parameter>
        <parameterName value="@message"/>
        <dbType value="String"/>
        <size value="4000"/>
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message"/>
        </layout>
      </parameter>
 
      <parameter>
        <parameterName value="@exception"/>
        <dbType value="String"/>
        <size value="2000"/>
        <layout type="log4net.Layout.ExceptionLayout"/>
      </parameter>
 
    </appender>
 
 
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="c:\temp\log-file.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
 
    <root>
 
      <level value="ALL"/>
 
      <appender-ref ref="AdoNetAppender"/>
      <appender-ref ref="FileAppender"/>
 
    </root>
 
  </log4net>

Tags:

SQL Deleting Duplicate Rows

by ebarcza 4/5/2012 5:35:00 AM

Here is a SQL Example for deleting duplicate rows in a database.

  1. find them using appropriate group by and having clauses
    Select OperatorID, LocationID, ProdMonth, ProdYear, Count(*) as cnt   from CrudeDeals 
    where ProdMonth = 3 and ProdYear = 2012
    Group by OperatorID, LocationID, ProdMonth, ProdYear
    Having Count(*) > 1
  2. Isolate the first PKID of each of the duplicate Records sets
    Select MIN(CrudeDealID),OperatorID, LocationID, ProdMonth, ProdYear, Count(*) as cnt   from CrudeDeals 
    where ProdMonth = 3 and ProdYear = 2012
    Group by OperatorID, LocationID, ProdMonth, ProdYear
    Having Count(*) > 1
  3. Now Delete the first record of each of the duplicate sets
    Delete CrudeDeals where CrudeDealID in(
    Select MIN(CrudeDealID)  from CrudeDeals 
    where ProdMonth = 5 and ProdYear = 2012
    Group by OperatorID, LocationID, ProdMonth, ProdYear
    Having Count(*) > 1)

    BOOM! no more dups
Note that the first two SQL statement are really just affirming the data sets that you are about to delete. All the work could be done with Step 3 if you are cocky enough in your coding ability to pull the trigger without first inpsecting what records it will delete. So if you've got the balls, skip right to step 3!

Tags:

SQL Server Reporting Services

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About the author

Name of author Author name
Something about me and what I do.

E-mail me Send mail

Calendar

<<  September 2017  >>
MoTuWeThFrSaSu
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

View posts in large calendar

Recent comments

Tags

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2017

Sign in