Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, July 2, 2015

How to get image URL via C# from site-core

This is just a quick post to show how to get image URL via code behind C#.

This is mostly useful when you are binding children items to a repeater or returning image URL in a JSON web-service.

 public static string GetImageURL(Item currentItem)  
 {  
      string imageURL = string.Empty;  
      Sitecore.Data.Fields.ImageField imageField = currentItem.Fields["Image"];  
      if (imageField != null && imageField.MediaItem != null)  
      {  
       Sitecore.Data.Items.MediaItem image = new Sitecore.Data.Items.MediaItem(imageField.MediaItem);  
       imageURL = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(image));  
      }  
 return imageURL;  
 }  


Special Thanks To : 

Tuesday, June 16, 2009

To Create a DropDownList from an ENUM

You have an 'Enum' defined as follows:
public enum CompanyAddressType
{
Unknown = 0,
Primary = 1,
Warehouse = 2,
Distribution_Center = 3,
Cross_Dock = 4
}


You want to iterate through the list and put the data into an asp.net DropDownList.

Here is the simple code:


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] names = Enum.GetNames(typeof (CompanyAddressType));
var values = (CompanyAddressType[]) Enum.GetValues(typeof (CompanyAddressType));
for (int i = 0; i < names.Length; i++)
{
DropDownListCompanyAddressType.Items.Add(new ListItem(names[i], values.ToString()));
}
}
}

There are probably easier ways to do it, but this works.


Use the tips!

Tuesday, February 24, 2009

Online convertion tools from C# to VB.NET and VB.NET to C#

Online convertion tools for C# to VB.NET and VB.NET to C#.

Use the following tools for converting C# code to VB.NET code and from VB.NET to C# code. Its very efficient and great tools available as of now. These tools are more reliable even for .Net 3.5 except for LINQ.

Simply paste in your C# code , and this free utility will automatically convert it to its equivalent in VB.NET.
http://www.developerfusion.com/tools/convert/csharp-to-vb/

Simply paste in your VB.NET code , and this free utility will automatically convert it to its equivalent in C#.
http://www.developerfusion.com/tools/convert/vb-to-csharp/

Happy Coding...

Thursday, December 25, 2008

C# array in descending or reverse order

How do you sort a C# array in descending or reverse order? A simple way is to sort the array in ascending order, then reverse it:
int[] intArray = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>( intArray );
Array.Reverse( intArray );
Of course, this is not efficient for large arrays.

A better approach is to create a custom Comparer. Following is a nice generics class that will sort an array in descending order. Note that the object type must be comparable (inherit from IComparable) as any useful class should.

Here’s a simple web application to test it:

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="SortSample.aspx.cs" Inherits="SampleApplication.SortSample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sort Ascending /Descending Order by Generic</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;

namespace SampleApplication.
{
public partial class SortSample: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int[] intArray = new int[] { 3, 1, 4, 5, 2 };
char[] charArray = new char[] { 'r', '1', 'f', 'c', 'x' };
string[] stringArray = new string[] { "array item 1", "array item 2", "array item 3", "array item 4", "array item 5" };

ArraySorter<int>.SortDescending(intArray);
ArraySorter<char>.SortDescending(charArray);
ArraySorter<string>.SortDescending(stringArray);

BindDropDownList(DropDownList1, intArray);
BindDropDownList(DropDownList2, charArray);
BindDropDownList(DropDownList3, stringArray);
}

private static void BindDropDownList(BaseDataBoundControl ddl, Array arr)
{
if(ddl !=null && arr !=null && arr.Length>0)
{
ddl.DataSource = arr;
ddl.DataBind();
}
}
static public class ArraySorter<T> where T : IComparable
{
static public void SortDescending(T[] array)
{
Array.Sort<T>(array, s_Comparer);
}

static private readonly ReverseComparer s_Comparer = new ReverseComparer();

private class ReverseComparer : IComparer<T>
{
public int Compare(T object1, T object2)
{
return -((IComparable)object1).CompareTo(object2);
}
}
}

}
}

I hope it will help you in someway.

Happy Coding!!!

Saturday, December 20, 2008

Design Pattern - Abstract Factory Pattern

Today I'm going to write about one of the most popular patterns in the design patterns world - the abstract factory.

You can read my previous posts about design patterns here:
An abstract factory provides an interface for creating families of related objects without specifying their concrete classes.

The abstract factory dictates which products the concrete factories will produce. Each concrete factory can build different products of different types.

The only way to get the products by the client is through the factory which isolate the products definition and creation. Object creation has been abstracted and there is no need for hard-coded class names in the client code.

For an example, take a real-world demonstrates the Factory method offering flexibility in creating different documents. The derived Document classes Report and Resume instantiate extended versions of the Document class. Here, the Factory Method is called in the constructor of the Document base class.

using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatternConsole
{
/// <summary>
/// The 'Product' abstract class
/// </summary>
abstract class Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class SkillsPage : Page
{
}

/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class EducationPage : Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class ExperiencePage : Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class IntroductionPage : Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class ResultsPage : Page
{
}


/// <summary>
/// The 'Creator' abstract class
/// </summary>
abstract class Document
{
private List<Page> _pages = new List<Page>();

// Constructor calls abstract Factory method
public Document()
{
this.CreatePages();
}

public List<Page> Pages
{
get { return _pages; }
}

// Factory Method
public abstract void CreatePages();
}

/// <summary>
/// A 'ConcreteCreator' class
/// </summary>
class Resume : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new SkillsPage());
Pages.Add(new EducationPage());
Pages.Add(new ExperiencePage());
}
}

/// <summary>
/// A 'ConcreteCreator' class
/// </summary>
class Report : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new IntroductionPage());
Pages.Add(new ResultsPage());
}
}

class AbstractFactory
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Note: constructors call Factory Method
Document[] documents = new Document[2];
documents[0] = new Resume();
documents[1] = new Report();

// Display document pages
foreach (Document document in documents)
{
Console.WriteLine("\n" + document.GetType().Name + "--");
foreach (Page page in document.Pages)
{
Console.WriteLine(" " + page.GetType().Name);
}
}

// Wait for user
Console.ReadKey();
}
}
}

Output :

The benefits of using the pattern are the isolation of concrete classes, it makes it easy to exchange product families and it makes the products consistent.

The drawback of the pattern is that the support of new products is difficult.

Happy Coding!!!

Design Pattern - Singleton

Before we move to Singleton pattern, first we should know what is instantiation and how it will play main role in Singleton.

Please refer my previous post for basic information about Design Pattern if you needs.

Instantiation means creating an object using a class as a template. There are two approaches to instantiation:
  • Lazy instantiation
  • Eager instantiation

Lazy instantiation : a class is not instantiated until a request is made via the Singleton.Instance() method.
if (singleton == null)
{
singleton = new Singleton(); // lazy instantiation
Console.WriteLine ("Singleton instantiated");
}

This code is quite simple. If singleton is null, then the Singleton object has not yet been instantiated. And, if not, it is instantiated with the new operator. This is only done once; because, the next time the code is called, singleton will not be null.

Eager instantiation is still lazy, it will run the initializers whenever the class is instantiated or another static member is accessed.

public sealed class Singleton
{

//private static Singleton singleton;
private static readonly Singleton singleton = new Singleton(); // eager instantiation

static Singleton()
{
Console.WriteLine ("Singleton instantiated");
}

private Singleton() {} // private constructor

public static Singleton GetInstance()
{
//if (singleton == null)
//{
// singleton = new Singleton();
// Console.WriteLine ("Singleton instantiated");
//}
return singleton;
}
}

The only differences between this eager code and the previous lazy example is that Singleton is instantiated in the static initializer instead of in the Singleton.Instance() method; and, there is a static constructor. However, this implementation is thread safe.


Now we will move to singleton.

Singleton is a design pattern used to restrict the instantiation of a class to one object. It is one of the most used and well know design patterns in programming.

For an example, you may need a class that will contain the user information across the system, there is no need to create several instances of this class. The explanation of this will be given in this little sample below:

Step 1. DesignPatternTest.aspx

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="DesignPatternTest.aspx.cs"
Inherits="DesignPatternTest.SingletonSample" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Singleton</title>
</head>
<body>
<form id="form1" runat="server">
<div>
See the above Singleton output
</div>
</form>
</body>
</html>

Step 2. DesignPatternTest.aspx.cs
using System;

namespace DesignPatternTest
{
public partial class SingletonSample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Constructor is protected
// Prevented from using 'new' keyword
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();

if (s1 == s2)
Response.Write("s1 & s2 are the same instance");

s1.x = 100;
Response.Write("<br>s1.x=" + s1.x);

s2.x = 200;
Response.Write("<br>s2.x=" + s2.x);

// Updates to x are updating same instance
Response.Write("<br>s1.x=" + s1.x);
Response.Write("<br>s2.x=" + s2.x);

}
}

public class Singleton
{
// Variable
public int x = 0;

// Fields
private static Singleton instance;

// Empty Constructor
protected Singleton() { }

// Methods
public static Singleton Instance()
{
// Uses "Lazy initialization"
if (instance == null)
instance = new Singleton();

return instance;
}
}
}

See the output

Singleton can be used in many situations, for samples.
  • Caches
  • Loggers
  • Thread pools
  • Dialog boxes
  • Device drivers
Last but not least, singleton is a class which permits itself to be instantiated only once.

  • Has a private or protected constructor with no parameters.
  • Has a single, global means of access via a static method.
  • Cannot be subclassed nor instantiated with the new operator.
  • Uses lazy instantiation

Happy Coding!!!