Asp Net Source.com's BlogAspNetSource's Official Blog

asp.net source code blog

Categories

Archives

2/18/2010 - Why is there an ASP.NET account on my machine
1/16/2010 - How to Open a Redirect in a New Window
1/2/2010 - Convert string to datetime Using C#
12/8/2009 - Using ASP.NET FileUpload to work with Images
11/24/2009 - Detect and Replace URLs in Text using Regex
11/17/2009 - Display RSS Feeds Using XmlDataSource
11/12/2009 - Get Current Theme Programmatically
11/10/2009 - Add Default ListItem to a DropDownList Control
10/20/2009 - GridView with LINQ Programatically
9/28/2009 - Server.HtmlEncode vs HttpUtility.HtmlEncode
8/20/2009 - Get List of sub Directories
7/29/2009 - gridview hide header
7/27/2009 - EmptyDataText Property in the Repeater Control
7/11/2009 - XmlDataSource GridView Example
7/5/2009 - Displaying multiple static paths by single page
6/8/2009 - Categories of classes in the System.Security.Cryptography Namespace
6/1/2009 - Delayed Loading of Page Parts
5/7/2009 - Using MySql in ASP.NET project, cofiguring, exaples with SqlDataSource, GridView, etc
4/29/2009 - What Are You Coding Right Now
4/23/2009 - Concat Byte Arrays in C Sharp
4/13/2009 - Visual Studio 2010 is Coming
3/16/2009 - automatic refresh page in some interval with javascript
2/21/2009 - we have just launched a new asp.net related site
2/18/2009 - Try Catch vs. Using
2/10/2009 - How to Set Language in web.config
1/30/2009 - A New Site for Free Online Test for Developers
1/21/2009 - Easy way to send email from gmail account using ASP.NET 3.5
1/15/2009 - Easy way to Dispaly a Word Document in Web Page
12/20/2008 - Create Yes No Voting Control
12/20/2008 - Our Team
12/15/2008 - Select xml node by other node
12/3/2008 - Forget about tedious mistakes when Validate through W3C
11/19/2008 - Fields removed when Download our Products
11/13/2008 - How to select all text in textbox when it gets focus
11/7/2008 - LINQ DataContext Class
11/3/2008 - PNGs and Browser Support
10/28/2008 - Check site loading by different locations in the world
10/27/2008 - Fix the SQL Connection Problems
10/26/2008 - Encrypt Connection Information
10/25/2008 - Generate Sitemap for your Site
10/23/2008 - Introduction to Design Patterns
10/21/2008 - Differences between Components, Controls, and Behaviors
10/20/2008 - What Is LINQ to SQL
10/19/2008 - Evolution of SQL Server
10/16/2008 - Loading Master Pages Dynamically in ASP.NET 3.5
10/15/2008 - A Brief Overview of Validation in ASP.NET 3.5
10/14/2008 - Automatically Hiding the Login Control from Authenticated Users
10/9/2008 - Check the load time of your website
10/5/2008 - Screw it, Lets RE-Design it all
10/2/2008 - Additional ASP.NET AJAX Libraries
9/29/2008 - The Big Problem of WYSIWYG Editors
9/29/2008 - New Forum for ASP.NET and Web Started
9/25/2008 - Optimize Page Loading Part 2 - Tips When work with Images
9/23/2008 - 10 Design Tips
9/19/2008 - C Sharp Features in Framework 3.0
9/15/2008 - Optimize Page Loading - 20 General Tips and Tricks
9/7/2008 - what is asp.net
9/5/2008 - Why Client Validation is not enough to secure our web app
8/29/2008 - Optimize Page Loading when works with DataBase
8/20/2008 - Highlight text in GridView using javascript
8/4/2008 - ContentPlaceHolder in title tag, Is That Bug in VS 2008
8/1/2008 - Why should we use ResolveUrl
7/31/2008 - Guid.TryParse in Framework 3.5
7/30/2008 - Redirect to current page
7/28/2008 - Validate Max Length of TextBox text
7/24/2008 - Easiest way for Row Numbering in GridView
7/23/2008 - Framework 3.5 Disadvantage of lamda expressions
7/21/2008 - LINQ - display filed from parent table in LinqDataSource and GridView
7/17/2008 - LinqDataSource and Guid passed as QueryStringParameter
7/14/2008 - Inappropriate name of DetailsView in msdn
7/9/2008 - Hide form after user download file
7/7/2008 - Menu in Master Page. How to set selected item from Page
7/4/2008 - Overview of New in Framework 3.5
7/2/2008 - New in Framework 3.5 - Generic Class HashSet
7/2/2008 - Present XmlDataSource data with Repeater
7/1/2008 - How to Validate ImageButton control through W3C
6/30/2008 - Using Find Method in Generic Controls With VB.NET - List
6/30/2008 - Using Find Method in Generic Controls With CSharp - List of T
6/30/2008 - Script injections using ASP.NET

References

 
Category Name: csharp
 
posted by Tihomir Ivanov on 02 January 2010 13:37
Posted in: csharp 

Sometimes you may have strings to represent dates (ex. 20100102 that represents 2010 January 2), here's an example how it can be converted to DateTime:

string dtString = "20100102";

IFormatProvider culture = new CultureInfo("en-EN", false);

DateTime dt = DateTime.ParseExact(dtString, "yyyyMMdd", culture, DateTimeStyles.NoCurrentDateDefault);

Now, if you want to convert DateTime variable to string in the format above, here's an example how it can be done:

String dtNewString = String.Format("{0:dd/MM/yyyy}", dt);

 

posted by Tihomir Ivanov on 24 November 2009 16:13
Posted in: csharp 

Here's a simple example how you can detect URLs in some text and replace them with html code for hyperlinks:


string someText = "here's a simple text that contains urls in it like http://www.aspnetsource.com or http://aspnetsource.com or http://aspnetsource.com";

// we create a Regex object with pattern to detect URLs
Regex reg = new Regex(@"((http|https|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))*[\w\d:#@%/;$()~_?\+-=\\\.&]*)");

string htmText = reg.Replace(someText, "<a href=\"$1\">$1</a>");

/* now htmlText contains formatted html code with hrefs:

here's a simple text that contains urls in it like <a href="http://www.aspnetsource.com">http://www.aspnetsource.com</a> or <a href="http://aspnetsource.com">http://aspnetsource.com</a> or <a href="http://aspnetsource.com">http://aspnetsource.com</a>

*/

posted by Tihomir Ivanov on 23 April 2009 10:21
Posted in: csharp 

In my work I had to concatenate two byte arrays but,
unfortunately, it seems that there's no elegant way to do
concat of two byte arrays in "C#" :(

I'd offer you a suggestion for doing it,
just copy-paste this simpe function in your project:

public byte[] ConcatByteArrays(byte[] a, int aSize, byte[] b, int bSize)
{
byte[] buff = new byte[aSize + bSize];
for(int i=0; i<aSize; i++)
buff[i] = a[i];
for(int i=0; i<bSize; i++)
buff[i+aSize] = b[i];
return buff;
}

 

posted by Tihomir Ivanov on 18 February 2009 16:22
Posted in: csharp asp.net 

Maybe, you wonder which is better choice: "try/catch" or "using" ?

well, it seem that they're really different from each other:

The "using" statement could be useful in:

1. Whenever an exception occurs, the using block takes care of closing connections like database connections, IO connections etc.
2. It also safely disposes the relevant objects

Note*: Only objects that implement IDisposable interface can be used in Using block!

The "try/catch" is used for any error occurred you can catch and display the message to the user.

So, I think the best answer of the question is: Use both of them:

using (OdbcConnection conn = new OdbcConnection(connectionString))
{
       try
       {
              dadapter.SelectCommand.Connection = conn;
               
              OdbcCommandBuilder builder = new OdbcCommandBuilder( dadapter );

              conn.Open();
              dadapter.Update(dset, "payunit");
         }
         catch ( Exception ex )
         {
                  //  exception handling code.    
         }
         finally
         {
                 conn.Close();
         }
   }      //  conn object is disposed. 

 

posted by Tihomir Ivanov on 19 September 2008 15:52
Posted in: csharp 

Here's list of new features of C# language in Framework 3.0.

1. Implicitly Typed Local Variables

You can use implicitly-typed local variables to store anonymous types. You can also use them in any other situation in which you want the compiler to determine the type of a local variable (in other words a variable declared at method scope). The following examples show how to use implicitly typed variables in both scenarios.

var developerNames =
from developer in developers
where developer.Language.Equals("C#")
select developer.FirstName + " " + developer.LastName;

foreach (string str in developerNames)
{
Console.WriteLine(str);
}

 

2. Implicitly Typed Arrays

You can also create an implicitly-typed array in which the type of the array instance is inferred from the elements specified in the array initializer. The rules for any implicitly-typed variable also apply to implicitly-typed arrays.

var ourSite = new[] { "asp", "net", "source", ".", "com" };

 

3. Auto-Implemented Properties

Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.

public class Developer
{
public string Language { get; set; }
public string Name { get; set; }
}

 

4. Additional Object Initializers Way

You can initialize new objects in easiest way:

...

Developer dev = new Developer { Language = "C#", Name = "Ivanov" };

 

5. Additional Arrays and Collections Initializers Way

Developer[] devs = new Developer[] {
new Developer { Language = "C#", Name = "Tihomir" },
new Developer { Language = "VB.NET", Name = "Ivanov" }
};

 

6. Extension Methods

Now you can "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

public static bool IsDotNetDeveloper(this Developer dev)
{
return dev.Language.Equals("C#") || dev.Language.Equals("VB.NET");
}

...

Developer dev = new Developer { Language = "C#", Name = "Ivanov" };

bool isDotNet = dev.IsDotNetDeveloper();

 

7. Anonymous types

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level.

var v = new { Language1 = "C#", Language2 = "VB.NET" };

 

8. Lambda Expressions

When '=>' is used that's lambda operator. It is used in lambda expressions to separate the input variables on the left side from the lambda body on the right side. Lambda expressions are inline expressions similar to anonymous methods but more flexible.

string[] languages = { "C++", "C#", "VB.NET" };

int min = languages.Min(l => l.Length);

 

9. Query Keywords

- from - Specifies a data source and a range variable (similar to an iteration variable).

- where - Filters source elements based on one or more Boolean expressions separated by logical AND and OR operators ( && or || ).

   select - Specifies the type and shape that the elements in the returned sequence will have when the query is executed.

   group - Groups query results according to a specified key value.

   into - Provides an identifier that can serve as a reference to the results of a join, group or select clause.

   orderby - Sorts query results in ascending or descending order based on the default comparer for the element type.

   join - Joins two data sources based on an equality comparison between two specified matching criteria.

   let - Introduces a range variable to store sub-expression results in a query expression.

string[] languages = { "C++", "C#", "VB.NET" };

var dotnets = from lang in languages
where lang.Equals("C#") || lang.Equals("VB.NET")
select lang;

foreach (var dotnet in dotnets)
{
Console.WriteLine(dotnets);
}

 

10. Partial Method

A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time.

partial class YourClass
{
  partial void SomeMethod(int i);
}

// This part can be in a separate file.
partial class YourClass
{
  // Comment out this method and the program
  // will still compile.
  partial void SomeMethod(int i)
  {
    Console.WriteLine("AspNetSource.com visit #{0}", i);
  }
}

That's All. Happy Coding :)

posted by Tihomir Ivanov on 31 July 2008 11:00
Posted in: csharp 

Unfortunately, method Guid.TryParse(string s, out Guid result) doesn't exist in .net, event in Framework 3.5 :(

But it's easy to write our method which tries to parse Guid:

Example 1:

bool TryParseGuid(string s, out Guid result)
{
 bool parseResult = false; 
 result = Guid.Empty; 
 try
 {
  result = new Guid(s);
  parseResult = true;
 }
 catch (Exception)
 {}
 return parseResult;
}

First example work but it looks little 'ugly', so this method could be written in more intelligent way:

Example 2:

public bool GuidTryParse(string s, out Guid result)
{
 bool parseResult = false;
 result = Guid.Empty;
 if (!string.IsNullOrEmpty(s))
 {
  Regex format = new Regex(
   "^[A-Fa-f0-9]{32}$|" +
   "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
   "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$");
  Match match = format.Match(s);
  if (match.Success)
  {
   result = new Guid(s);
   parseResult = true;
  }
 }
 return parseResult;
}

 

That's all! Happy coding!

posted by Tihomir Ivanov on 23 July 2008 03:11
Posted in: csharp 

something very cool thing in asp.net developing with Visual Studio is the debugger: in QuickWatch you can write everyting: variables, call functions to see result by them, ... everything, ... Well, almost everything: in new debugger: you cannot see result of lambda expressions:

it's not big deal but until this moment I've used to 'quickwatching' everything, but now the debugging will be a little different :(

That's all! Happy coding!

12


 
Asp Net Source.com


 
Our Sponsors:  Asp.net file upload component  |   Flash file uploader