Sunday, July 22, 2012

C# - Convert String to DateTime using ParseExact() method of DateTime



It is a common requirement to convert a Date/Time you have as a string to .NET native DateTime type.
The point to note here is to convey to the .NET Framework regarding the Date Format you provide as the input string. ParseExact() method of DateTime Type comes handy here.
Below is the solution to these

Convert String to DateTime in C# .NET
// String to DateTime
String dateText;
dateText = "1999-09-01 21:34 PM"; // Provide this according to your computer personal settings

DateTime myDate;
myDate = new DateTime();
myDate = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null);

Convert DateTime to String in C# .NET
//DateTime to String
myDate = new DateTime(1999, 09, 01, 21, 34, 00);
String dateText = myDate.ToString("yyyy-MM-dd HH:mm tt");

Tuesday, July 10, 2012

C# - Linq - Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'int'


Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'

Issue:
In Linq queries sometimes you get the exception "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'". A scenario where you find this exception is as illustrated below:

int domainId = from p in pages
               where p.Value.aspxFile == pageFileName
               select p.Value.domain;

Logically I know there will only be one value being returned from this Linq Query statement, so it should work for me. But by syntax, this Linq statement returns type IEnumerable Collection.

Solution:

int domainId = (from p in pages
        where p.Value.aspxFile == pageFileName
        select p.Value.domain).First();

This solves my issue and it will return only one object and not a collection. The object type is determined by the compiler at compile time which will be int in my case.

You can use .First() or FirstOrDefault() or Single(). But for Single() make sure that there is exactly only one element in the list.

Monday, April 2, 2012

ASP.NET AJAX not working on Google Chrome and Safari - Update panel/Popup Extender.


Issue:
Recently i faced this issue when working with ASP.NET Ajax Updatepanel and Popup extender. The Popup was always visible and took a fixed space on the page like a normal div.

Solution:
Added the below javascript code to a .js file.
Sys.Browser.WebKit = {}; //Safari 3 is considered WebKit
if( navigator.userAgent.indexOf( 'WebKit/' ) > -1 )
{
  Sys.Browser.agent = Sys.Browser.WebKit;
  Sys.Browser.version = parseFloat( navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
  Sys.Browser.name = 'WebKit';
}

Refer the .js file in the ScriptManager.
<ajax:ToolkitScriptManager ID="scripts" runat="server" ScriptMode="Release" EnableHistory="true"
EnableSecureHistoryState="false" EnablePageMethods="True" CombineScripts="true"
OnAsyncPostBackError="Page_OnAsyncError" OnNavigate="OnHistoryNavigate">
    <Scripts>
        <asp:ScriptReference Path="~/js/webkit.js" />
    </Scripts>
</ajax:ToolkitScriptManager>

Sunday, April 1, 2012

JAVASCRIPT - How to remove last character from string


A common requirement, I have been approached is to have a javascript function to remove last character of a string. This is usually for some delimited string like a comma separated string.

var yourStr = "1, 2, 3, 4,"    
var yourstrLen =  yourStr.length;
yourStr =  yourStr.slice(0,yourstrLen-1);
alert (yourStr);


Instead of 
    yourStr.slice(0,yourstrLen-1);
    yourStr.slice(0, 1); is also equally acceptable, because negative value sets offset from the end of the string.

Monday, March 26, 2012

SQL SERVER – Find First Day / Last Day of any month - Current - Previous - Next



Use the below queries as a sample to find the First day and Last Day of any month.
The sample below shows the First and Last days for previous and next months.


DECLARE @today DATETIME
SELECT @today = GETDATE();
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@today)),@today),101) ,
'Last Day of Previous Month'
UNION ALL
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@today)-1),@today),101) AS Date_Value,
'First Day of Current Month' AS Date_Type
UNION ALL
SELECT CONVERT(VARCHAR(25),@today,101) AS Date_Value, 'Today' AS Date_Type
UNION ALL
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@today))),DATEADD(mm,1,@today)),101) ,
'Last Day of Current Month'
UNION ALL
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@today))-1),DATEADD(mm,1,@today)),101) ,
'First Day of Next Month'
UNION ALL
SELECT CONVERT(VARCHAR(25),DATEADD(dd,1-day((DATEADD(mm,-1,@today))),DATEADD(mm,-1,@today)),101) AS Date_Value,
'First Day of Previous Month' AS Date_Type

Alternatively you can also use the below code, this gives time precision also:

----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth


Sunday, March 25, 2012

SQL SERVER - How to use TRANSACTION in Stored Procedure | COMMIT, ROLLBACK


A SQL Server Transaction in a Stored procedure can be used to do a batch of queries especially INSERT / UPDATE / DELETE. The changes made to data in a transaction will persist only once COMMITTED. Hope the sample below helps you to get a practical idea about its usage.

BEGIN TRAN

INSERT INTO Person(Name, Age, Phone, Address)
VALUES ('Gates',50, '800-MSFT', 'Redmond, Washington, U.S')

IF @@ERROR <> 0
ROLLBACK TRAN
ELSE
        COMMIT TRAN

ASP.NET - Adding AjaxToolkit Accordion Pane Dynamically in C#

Issue:
How to add AjaxToolkit Accordion Pane Dynamically in C#

Solution:
In the below code, it iterate thought a List/Dictionary of custom object BannerList and creates Accordion Panes dynamically. The code is part of a sample I was working on. But it will help you understand the idea.


foreach (KeyValuePair<int, List<Banner>> entry in BannerList)
{
    AccordionPane ap1 = new AccordionPane();
    ap1.HeaderContainer.Controls.Add(new LiteralControl(Countries[entry.Key].ToUpper()));
             
    CheckBoxList chkLst = new CheckBoxList();
    chkLst.ID = "chkBoxLst" + Countries[entry.Key];
    chkLst.RepeatColumns = 5;
    foreach(Banner b in entry.Value)
    {
        chkLst.Items.Add(new ListItem(b.BannerName, b.BannerID.ToString()));
    }
    Button btnSave = new Button();
    btnSave.ID = "btnSave" + Countries[entry.Key];
    btnSave.Text = "Save";
    Button btnCancel = new Button();
    btnCancel.ID = "btnCancel" + Countries[entry.Key];
    btnCancel.Text = "Cancel";
    ap1.ContentContainer.Controls.Add(chkLst);
    ap1.ContentContainer.Controls.Add(btnSave);
    ap1.ContentContainer.Controls.Add(btnCancel);
    acc1.Panes.Add(ap1);
}