Most of C# developers are familiar with this String.split() method. I have found some useful overloads for split method of the string class split the string in array of string.
Example 1:
String.Split( char[])
Code:
string words = "string1,string2,string3,,string4 string5.";
string [] split = words.Split(new Char [] {' ', ','});
Above code create a string array which has
//result
split[0]=string1
split[1]=string2
split[2]=string3
split[3]=
split[4]=string4
split[5]=string5
but What If I want to remove empty string from the array when I split string.
Solution to this problem is to make use of second overload method of the the string Split where you can specify the option to remove string. So above code is rewritten as
Overload method with option
String.Split(Char[], StringSplitOptions)
Code:
string words = "string1,string2,string3,,string4 string5.";
string [] split = words.Split(new Char [] {' ', ','},StringSplitOptions.RemoveEmptyEntries);
Return split array->
//result
split[0]=string1
split[1]=string2
split[2]=string3
split[3]=string4
split[4]=string5
Example 2:
Now consider case where I have to limit no of return string. Consider for example
string a = "key:Testkey, Value : testValue1,testValue2";
Now I have to get the key:Testkeyin string 1 and Value : testValue1,testValue2in string 2.
Overload function to split string in limited no. of string
Split(Char[], Int32)
Code:
string a = "key: Testkey, Value : testValue1,testValue2";
string [] split = words.Split(new Char [] {','},2);
Return split array->
//result
split[0]= "key: Testkey";
split[1]= "Value : testValue1,testValue2";
For more information:
String.Split Method (Char(), Int32):
http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx
String.Split Method (Char(), Int32, StringSplitOptions):
http://msdn.microsoft.com/en-us/library/ms131450.aspx
Sharing real-world experiences about C#, Dynamics CRM, Dynamics 365, Dynamics NAV/Business Central, SharePoint,PowerBI,ASP.net and more...
Tuesday, January 31, 2012
RequiredField Validator not working with CKEditor in ASP.Net
Last month I had worked on a project where we were using CKEDITOR. For validation using asp.net required field validator. It is working for all control but unfortunately required field validator is not working for CKEDITOR.
After searching I have got the reason and solution for this.
Reason:
The requiredfield validator control will not work properly when it is used with a textarea that is configured with CKEditor. This is due to the fact that, the CKEditor content will not be synched to the page element(textarea) properly when the validator control fire.
Solution:
To overcome this difficulty, we need to call the method updateElement() in order to sync or post the content back to the textarea. The below code does that,
<head>
<script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckeditor/adapters/jquery.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#TextBox1').ckeditor();
});
function UpdateContent() {
var ckeditorinstance = $('#TextBox1').ckeditorGet();
ckeditorinstance.updateElement();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="No content in CKEditor!"></asp:RequiredFieldValidator>
</div>
<asp:Button ID="btnSave" OnClientClick="javascript:UpdateContent()" runat="server" Text="Save" onclick="btnSave_Click" />
</body>
In the above code, the javascript method UpdateContent() will update the page elements with ckeditor content whenever tha Save button is clicked. Thus, on save click the requiredfield validator control will fire properly now.
After searching I have got the reason and solution for this.
Reason:
The requiredfield validator control will not work properly when it is used with a textarea that is configured with CKEditor. This is due to the fact that, the CKEditor content will not be synched to the page element(textarea) properly when the validator control fire.
Solution:
To overcome this difficulty, we need to call the method updateElement() in order to sync or post the content back to the textarea. The below code does that,
<head>
<script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckeditor/adapters/jquery.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#TextBox1').ckeditor();
});
function UpdateContent() {
var ckeditorinstance = $('#TextBox1').ckeditorGet();
ckeditorinstance.updateElement();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="No content in CKEditor!"></asp:RequiredFieldValidator>
</div>
<asp:Button ID="btnSave" OnClientClick="javascript:UpdateContent()" runat="server" Text="Save" onclick="btnSave_Click" />
</body>
In the above code, the javascript method UpdateContent() will update the page elements with ckeditor content whenever tha Save button is clicked. Thus, on save click the requiredfield validator control will fire properly now.
"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."
Very recently I have worked on asp.net MVC application. Everything is working fine for MVC v1. But when move to MVC v2 I have gotten this error-
"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."
After making some r & d I have found the solution:
Reason:
In MVC v2 they block Json for GET requests (as you can tell from the error) for security reasons.
If your JSON payload:
1.Contains sensitive non-public data
2.Returns an Array
3.Responds to a GET request
4.Browser making the request has JavaScript enabled (very likely the case)
5.Browser making the request supports the __defineSetter__ method.
Then the data is vulnerable to a JSON hijacking. Typically, it's not *your* data but the data of the users of your website.
For more details about JSON Hijacking.
Solution:
1.A possible solution I found online is to set the request to "POST" method instead of "GET" method.
2.If you want to override the behavior, check out the overload for Json that accepts a JsonRequestBehavior parameter.
public ActionResult Index()
{
//Return Json result using LINQ to SQL
//###################################################
//MVC 1.0 specific implementation - A JSON Result
//is returned.
//###################################################
//return new JsonResult
//{
// Data = (from p in Product.GetProductDataList()
// where p.ColorId == colorid
// select p).ToArray()
//};
//###################################################
//MVC RC2 specific implementation - A JSON Result
//is returned, and the AllowGet property is set for
//the JsonRequestBehavior.
//###################################################
var data = (from p in Product.GetProductDataList()
where p.ColorId == colorid
select p).ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."
After making some r & d I have found the solution:
Reason:
In MVC v2 they block Json for GET requests (as you can tell from the error) for security reasons.
If your JSON payload:
1.Contains sensitive non-public data
2.Returns an Array
3.Responds to a GET request
4.Browser making the request has JavaScript enabled (very likely the case)
5.Browser making the request supports the __defineSetter__ method.
Then the data is vulnerable to a JSON hijacking. Typically, it's not *your* data but the data of the users of your website.
For more details about JSON Hijacking.
Solution:
1.A possible solution I found online is to set the request to "POST" method instead of "GET" method.
2.If you want to override the behavior, check out the overload for Json that accepts a JsonRequestBehavior parameter.
public ActionResult Index()
{
//Return Json result using LINQ to SQL
//###################################################
//MVC 1.0 specific implementation - A JSON Result
//is returned.
//###################################################
//return new JsonResult
//{
// Data = (from p in Product.GetProductDataList()
// where p.ColorId == colorid
// select p).ToArray
//};
//###################################################
//MVC RC2 specific implementation - A JSON Result
//is returned, and the AllowGet property is set for
//the JsonRequestBehavior.
//###################################################
var data = (from p in Product.GetProductDataList()
where p.ColorId == colorid
select p).ToArray
return Json(data, JsonRequestBehavior.AllowGet);
}
Thursday, January 26, 2012
Stopwatch class to determine the execution time for an application
A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.
If you want to measure the time required for your programs written in the C# language. This could be for a micro-benchmark or for routine and continuous performance monitoring.
Example
First sample:
In this sample you must create Stopwatch as an instance. This makes it useful in multithreaded applications or websites.
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);//or do some work
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}
Second sample:
In this sample we use the StartNew method. This uses a creational design pattern to return a new instance from a static type method. It eliminates typing and simplifies your code.
class Program
{
static void Main(string[] args)
{
// Create new stopwatch
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
// Do something
// Stop timing
stopwatch.Stop();
// Write the results
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}
For more details please visits here.
If you want to measure the time required for your programs written in the C# language. This could be for a micro-benchmark or for routine and continuous performance monitoring.
Example
First sample:
In this sample you must create Stopwatch as an instance. This makes it useful in multithreaded applications or websites.
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);//or do some work
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}
Second sample:
In this sample we use the StartNew method. This uses a creational design pattern to return a new instance from a static type method. It eliminates typing and simplifies your code.
class Program
{
static void Main(string[] args)
{
// Create new stopwatch
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
// Do something
// Stop timing
stopwatch.Stop();
// Write the results
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}
For more details please visits here.
SQL Server case/when type conversion problem
In my last project I wrote a query where I have to sort data based on the user input but each column in table has different data type. So to meet with this type of requirement I have used case..when block of the sql server.
Problem: Sample query
DECLARE @sortby Varchar(10)
Set @sortby = 'A1'
Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime()
union
select 'A2','B2', GetDateTime()
) As d(String1,String2,DateCol)
Order by
Case
When @sortby = 'A1' then String2
When @sortby = 'B1' then String1
When @sortby = 'Date' then Date1
End
there is not syntax error when you check for the syntax error but when execute code you find there is error
ERROR:Conversion failed when converting datetime from character string.
the problem here is first two having databype Varchar and last one having datatype DateTime. So when you executing its found that one branch having datetime so its gives error even its not executing that.
Solution
First Solution
So to avoid this problem you require to convert dateTime to the string
DECLARE @sortby Varchar(10)
Set @sortby = 'A1'
Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime()
union
select 'A2','B2', GetDateTime()
) As d(String1,String2,DateCol)
Order by
Case
When @sortby = 'A1' then String2
When @sortby = 'B1' then String1
When @sortby = 'Date' then Cast(Date1 as varchar(20))
End
Second Solution
Divide the Case when in multiple statement
DECLARE @sortby Varchar(10)
Set @sortby = 'A1'
Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime()
union
select 'A2','B2', GetDateTime()
) As d(String1,String2,DateCol)
Order by
Case When @sortby = 'A1' then String2 End,
Case When @sortby = 'B1' then String1 End,
Case When @sortby = 'Date' then Date1 End
Problem: Sample query
DECLARE @sortby Varchar(10)
Set @sortby = 'A1'
Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime()
union
select 'A2','B2', GetDateTime()
) As d(String1,String2,DateCol)
Order by
Case
When @sortby = 'A1' then String2
When @sortby = 'B1' then String1
When @sortby = 'Date' then Date1
End
there is not syntax error when you check for the syntax error but when execute code you find there is error
ERROR:Conversion failed when converting datetime from character string.
the problem here is first two having databype Varchar and last one having datatype DateTime. So when you executing its found that one branch having datetime so its gives error even its not executing that.
Solution
First Solution
So to avoid this problem you require to convert dateTime to the string
DECLARE @sortby Varchar(10)
Set @sortby = 'A1'
Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime()
union
select 'A2','B2', GetDateTime()
) As d(String1,String2,DateCol)
Order by
Case
When @sortby = 'A1' then String2
When @sortby = 'B1' then String1
When @sortby = 'Date' then Cast(Date1 as varchar(20))
End
Second Solution
Divide the Case when in multiple statement
DECLARE @sortby Varchar(10)
Set @sortby = 'A1'
Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime()
union
select 'A2','B2', GetDateTime()
) As d(String1,String2,DateCol)
Order by
Case When @sortby = 'A1' then String2 End,
Case When @sortby = 'B1' then String1 End,
Case When @sortby = 'Date' then Date1 End
Thursday, January 19, 2012
Html stripper (Remove Html tag)
This is a common problem when we want to show any data in gridview(asp.net) or table or repeater it breaks the page or design of the page due to html tag inside the presented date.
It will also cause the problem if we want use CKEDITOR to insert data. Because when we insert anything using rich editor it is wrap the text with <p></p>. If we want to show partial of the string it will cause page break because last </p> is missing.
So to avoid this problem we need to strip the Html tag from the string. We can do it in various ways such as regular expression and character array.
Solution 1(Good):
using System.Text.RegularExpressions;
//Remove HTML from string with Regex.
public static string StripTagsRegex(string source)
{
return Regex.Replace(source, "<.*?>", string.Empty);
}
Solution 2(Better):
using System.Text.RegularExpressions;
// Compiled regular expression for performance.
static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
// Remove HTML from string with compiled Regex.
public static string StripTagsRegexCompiled(string source)
{
return _htmlRegex.Replace(source, string.Empty);
}
Solution 3:(Best)
//Remove HTML tags from string using char array.
public static string StripTagsCharArray(string source)
{
char[] array = new char[source.Length];
int arrayIndex = 0;
bool inside = false;
for (int i = 0; i < source.Length; i++) { char let = source[i]; if (let == '<') { inside = true; continue; } if (let == '>')
{
inside = false;
continue;
}
if (!inside)
{
array[arrayIndex] = let;
arrayIndex++;
}
}
return new string(array, 0, arrayIndex);
}
It will also cause the problem if we want use CKEDITOR to insert data. Because when we insert anything using rich editor it is wrap the text with <p></p>. If we want to show partial of the string it will cause page break because last </p> is missing.
So to avoid this problem we need to strip the Html tag from the string. We can do it in various ways such as regular expression and character array.
Solution 1(Good):
using System.Text.RegularExpressions;
//Remove HTML from string with Regex.
public static string StripTagsRegex(string source)
{
return Regex.Replace(source, "<.*?>", string.Empty);
}
Solution 2(Better):
using System.Text.RegularExpressions;
// Compiled regular expression for performance.
static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
// Remove HTML from string with compiled Regex.
public static string StripTagsRegexCompiled(string source)
{
return _htmlRegex.Replace(source, string.Empty);
}
Solution 3:(Best)
//Remove HTML tags from string using char array.
public static string StripTagsCharArray(string source)
{
char[] array = new char[source.Length];
int arrayIndex = 0;
bool inside = false;
for (int i = 0; i < source.Length; i++) { char let = source[i]; if (let == '<') { inside = true; continue; } if (let == '>')
{
inside = false;
continue;
}
if (!inside)
{
array[arrayIndex] = let;
arrayIndex++;
}
}
return new string(array, 0, arrayIndex);
}
Fixed problem for continuous string(long string without space) using regular expression
Last day I have faced a problem for a long string like(adfdsfsdfdsfdsfsdafdsfsdfsdfsdfsdfsdfsdfsdfsdffdsfsdfsdfsdafsdfsdfsdfsdfsdfsdafsdf) which make my application's UI design break. So to fixed this issue I have used regular expression which insert a space after n characters.
To insert a space after every n characters:
var newString = Regex.Replace(oldString, new string('.', n), m => m.Value + " ");
Sample solution:
string longWord = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaassssssssssssssssssssssssdddddddddddddddddddddddddddddaaaaaaaaaafffffffffffffffffffffffffadfdsfsdfdsfdsfsdafdsfsdfsdfsdfsdfsdfsdfsdfsdffdsfsdfsdfsdafsdfsdfsdfsdfsdfsdafsdffdsfdsfdsfsdf";
Regex.Replace(longWord, new string('.', 16), m => m.Value + " ");
In above image it shows that regex place a space after every 16 character for that long string.
To insert a space after every n characters:
var newString = Regex.Replace(oldString, new string('.', n), m => m.Value + " ");
Sample solution:
string longWord = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaassssssssssssssssssssssssdddddddddddddddddddddddddddddaaaaaaaaaafffffffffffffffffffffffffadfdsfsdfdsfdsfsdafdsfsdfsdfsdfsdfsdfsdfsdfsdffdsfsdfsdfsdafsdfsdfsdfsdfsdfsdafsdffdsfdsfdsfsdf";
Regex.Replace(longWord, new string('.', 16), m => m.Value + " ");
In above image it shows that regex place a space after every 16 character for that long string.
JavaScript parseInt() bug
Very recently I have faced a strange problem with JavaScript parseInt() function. It returns incorrect result when try to parse value like "08","09"...... But it works for "01" to "07".
So I have tried to find solution in community. Then find that this was a JavaScript bug.
Problem:
There is a "bug" with the parseInt JavaScript function. The bug is not something that will affect you very often, but it is something you should be aware of. We've seen the bug in every browser except Opera.
I've created a button to demonstrate the bug. The bug is that parseInt can return an incorrect value. For example, parseInt("08") results in 0 instead of 8. And parseInt("09") results in 0 instead of 9. The reason for this is because the zero in front is trying to tell the browser that this is an octal (base 8) number, and "08" and "09" are not valid octal numbers. The button below builds statements from parseInt("01") through parseInt("09") and shows what the resulting value is. But it also does parseFloat("01") through parseFloat("09"). This shows that the bug does not exist with parseFloat.
Solution:
parseInt(parseFloat(09))
Or,
parseInt(09, 10)
The "10" in the second example tells the browser that base-10 values should be used.
Hope that it will helpful for other developers.Thanks.
So I have tried to find solution in community. Then find that this was a JavaScript bug.
Problem:
There is a "bug" with the parseInt JavaScript function. The bug is not something that will affect you very often, but it is something you should be aware of. We've seen the bug in every browser except Opera.
I've created a button to demonstrate the bug. The bug is that parseInt can return an incorrect value. For example, parseInt("08") results in 0 instead of 8. And parseInt("09") results in 0 instead of 9. The reason for this is because the zero in front is trying to tell the browser that this is an octal (base 8) number, and "08" and "09" are not valid octal numbers. The button below builds statements from parseInt("01") through parseInt("09") and shows what the resulting value is. But it also does parseFloat("01") through parseFloat("09"). This shows that the bug does not exist with parseFloat.
Solution:
parseInt(parseFloat(09))
Or,
parseInt(09, 10)
The "10" in the second example tells the browser that base-10 values should be used.
Hope that it will helpful for other developers.Thanks.
Subscribe to:
Posts (Atom)
Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'
Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...
-
The CheckBoxList control in ASP.NET 2.0 is one of the useful control for asp.net developer. But it is not so easy(also not complicated :))to...
-
There are various ways to use Single Sign on(SSO) in asp.net web application. We can use cookies, session (state server), SAML and web serv...
-
Problem: Today I have faced a new problem(new for me), when I press save button it works fine and then refresh(F5 or Refresh button on brow...