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

Thursday, December 6, 2012

Creating Dynamic Predicates Using Predicate Builder

IQueryable SearchProducts (params string[] keywords)
{
  var predicate = PredicateBuilder.False();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }
  return dataContext.Products.Where (predicate);
}


see C# in a Nutshell

Friday, September 7, 2012

Compiling Anywhere Anytime Online

Programr.comSo have you ever had a great idea? I had this great idea while talking with another developer at work today.  What if you could write and compile code online (in the cloud) rather than in an IDE (integrated development environment)? 

What a great idea, right?  Then the after thougth of, "I'm sure I'm not the only one who has thought of this."  After quick search I found quite a few sites that allowed a user to develope and compile their code right in the browser: codepad, programr, compilify, compilr, etc.

The one I liked the most was PROGRAMR.  I could develope in the language of my choice:  C#, Java, Flex, JavaScript, Objective-C, C++, T-SQL, among others.  What more could I ask for? 

Now I can write and compile code anywhere and anytime I wanted as long as I'm online.

Let me know what you think, and let me know if you find one that you think is better.  Happy hacking!

Saturday, May 12, 2012

What's in My GAC?

 Having your assemblies in the GAC can be useful, but how do I find out what's in my GAC?

You can view assemblies in the GAC by bringing up the "Run Command" in windows ('Windows Key+R) then type: 'C:\Windows\assembly\gac_msil' to see the assemblies in the GAC.


Wha't s an assembly?
What is the GAC?
How to install an Assembly to the GAC?

Tuesday, October 19, 2010

New Collaboration In Technology

Sometimes technologies seem to cause conflict, and epic battles erupt between companies, leaving their users and developers baffled.

Every once in a while these same companies and technologies find themselves in harmony, leaving their users and developer just as baffled.

Apple is getting along with Adobe?
ActionScript 3.0 IDE was written in C#?

Wednesday, June 16, 2010

Extending With Extension Methods

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

namespace DripCode.Text
{
public static class ExtensionMethods
{
public static Boolean ContainsAt(this string line, string template, int location)
{
return line.Contains(template) && line.Length >= template.Length + location && line.Substring(location, template.Length) == template;
}
}
}

Usage:

string Test = "hello world!"
Console.WriteLine(Test.ContainsAt("hello",0).ToString());
Console.WriteLine(Test.ContainsAt("world",6).ToString());


Extension Methods (C# Programming Guide)

Sunday, January 24, 2010

iPhone Application written in C#

If you are a C# developer you can also create iPhone application without learning Objective C. Check out MonoTouch.

Tuesday, November 24, 2009

LINQ Equivalent To A T-SQL IN


SELECT * FROM MemberInfomation WHERE @samAccount IN ('adf','asfd','wqewe')
Similarly you can do a IN like filter in LINQ:

public List GetInformation(String[] samAccounts)
{
SomeDataContextdc = new SomeDataContext();
return dc.MemberInfomation.Where(
o => samAccounts.Contains(o.samaccount)
).ToList();
}
Got help from here.

Unit Testing Thrown Exceptions

  #region Throwing Exception Tests
        private void MethodToTest()
        {
            throw new ArgumentException("blah");
        }

Using ExpectedException attribute to test exception throwing is pretty straight forward:
        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void Test_ExceptionThrown_Attribute()
        {
            try
            {
                MethodToTest();
            }
            catch (Exception ex)
            {
                if (ex.Message == "blah") //test message value
                    throw new ArgumentException(ex.Message);
            }
        }

Another approach might be:

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void Test_ExceptionThrown_Attribute_Function()
        {
            VerifyExceptionThrown_Throw(() => MethodToTest(), "blah"); // simple, single line, and generic.
        }


        // Method accepts an action delegate, a generic Exception type, and an exception message to check
        public static void VerifyExceptionThrown_Throw(Action action, String exMessage)
           where TException : Exception
        {
            // Verify arguments - action can't be null
            if (action == null)
                throw new ArgumentException("Action to test cannot be null!");

            // Verify arguments - TException cannot be of type Exception
            if (typeof(TException).Equals(typeof(Exception)))
                throw new ArgumentException("TException type cannot be of type Exception");

            // Actually call it
            try
            {
                action();
            }
            catch (TException ex)
            {
                if (ex.Message == exMessage)
                {
                    throw new ArgumentException("good job"); //we must rethrow an exception because of ExpectedException attribute 
                }
            }

            // If it gets here, fail the test
            Assert.Fail("Action does not throw the exception expected");
        }

Test for exception throwing without the ExpectedException attribute:

        //
        [TestMethod]
        public void Test_ExceptionThrown_NoAttribute()
        {
            try
            {
                MethodToTest();
                Assert.Fail("Action does not throw the exception expected");
            }
            catch (ArgumentException ex)//specifing the type of exception to test for
            {
                if (ex.Message != "blah") //test message value
                    Assert.Fail("Action does not throw the exception expected"); //failed 
            }
        }

My preferred way to test exceptions:
        [TestMethod]
        public void Test_ExceptionThrown_NoAttribute_Function()
        {
            VerifyExceptionThrown_NoThrow(() => MethodToTest(), "blah"); //simple, generic, message parameter is optional... and the TestMethod doesn't need the attribute
        }


        // Method accepts an action delegate, a generic Exception type, and an exception message to check (optional)
        public static void VerifyExceptionThrown_NoThrow(Action action, String exMessage)
           where TException : Exception
        {
            // Verify arguments - action can't be null
            if (action == null)
                throw new ArgumentException("Action to test cannot be null!");

            // Verify arguments - TException cannot be of type Exception
            if (typeof(TException).Equals(typeof(Exception)))
                throw new ArgumentException("TException type cannot be of type Exception");

            // Actually call it
            try
            {
                action();
            }
            catch (TException ex)
            {
                if (exMessage == null) //don't want to consider the message
                {
                    return;
                }
                else //otherwise consider the message 
                {
                    if (ex.Message == exMessage)
                    {
                        return;
                    }
                }
            }

            // If it gets here, fail the test
            Assert.Fail("Action does not throw the exception expected");
        }
        #endregion

I used code from this example here.

Thursday, October 1, 2009

Google Base API - Insert a Housing Entry via a Batch Feed

I've been looking for a straight forward .Net example on how to upload a "Housing" item entry via a batch in the Google Base API, but to no avail. Mind you this is for Australia, so the required attributes are a bit different for the United States. After talking with someone at Google, we got it sorted out. Here's my example:

using Google.GData.Client;
using Google.GData.GoogleBase;


public static class GoogleBaseFacade
{
private static GBaseService service;

private static void Connect()
{
if (service == null)
{
service = new GBaseService("TEST - Homes for Sale", <google key>);
service.setUserCredentials(<login>, <password>);
service.NewAtomEntry += new FeedParserEventHandler(service_NewAtomEntry);
}
}

static void service_NewAtomEntry(object sender, FeedParserEventArgs e)
{
if (e.Feed != null && e.Feed.Entries != null && e.Feed.Entries.Count > 0)
{
foreach (AtomEntry entry in e.Feed.Entries)
{
if (entry.BatchData != null)
{
Console.WriteLine("New Entry STATUS CODE: " + entry.BatchData.Status.Code.ToString());
}
else if (entry.Id != null && entry.Id.Uri != null)
{

Console.WriteLine("New Entry URI: " + entry.Id.Uri);
}
else
{
Console.WriteLine("New Entry ???");
}
}
}
else
{
Console.WriteLine("No Feed or Entries in feed. Possible single entry");
}
}

public static void AddAHome()
{
Connect();
//create an entry
GBaseEntry entry = new GBaseEntry();
AtomPerson author = new AtomPerson(AtomPersonType.Author,"James Smith");
author.Email="jamessmith@example.com";
entry.Authors.Add(author);
entry.GBaseAttributes.AddTextAttribute("target_country", "AU");
entry.GBaseAttributes.ItemType = "Housing";
entry.GBaseAttributes.AddNumberAttribute("bathrooms", 2);
entry.GBaseAttributes.AddNumberAttribute("bedrooms", 3);
entry.GBaseAttributes.AddTextAttribute("description", "A fantastic underground house.");
entry.Links.Add(new AtomLink("http://www.velociraptorz.org"));
entry.GBaseAttributes.AddTextAttribute("listing_type", "residential for sale");
entry.GBaseAttributes.AddNumberAttribute("price", 1200000);
entry.GBaseAttributes.AddTextAttribute("property_type", "house");
entry.GBaseAttributes.Location = "1 Market St, Sydney, NSW, 2000";
entry.Title.Text = "A safe haven, underground.";
entry.BatchData = new GDataBatchEntryData("blahblah", GDataBatchOperationType.insert);
entry.BatchData.Id = "batch1234";

AtomFeed batchFeed = new AtomFeed(GBaseUriFactory.Default.ItemsFeedUri, service);
batchFeed.Entries.Add(entry);

GBaseFeed returnFeed = service.Batch(batchFeed, GBaseUriFactory.Default.ItemsFeedBatchUri) as GBaseFeed;
}
}


Here are some useful links:


I hope this helps someone.

Tuesday, April 28, 2009

Thursday, April 23, 2009

Be Coded or Be Cast Out - a XMLInclude and Casting issue

Problem:

When you don't have access to the code of a class in a webservice and you inherit from that class, you can't use xmlinclude. The reason is you need to put the XMLInclude attribute on the base class.

So when I pass my derived class to the webmethod, it complains.

Fine no worries. I will cast it to the base class type and that should work, right? Wrong!

Objects are reference types and the variable that you are assinging the cast to, even if it's defined as the base class, in pointing to the derived class has the type of the derived class. Even though you can only access the properties and methods of the base class at design time (makes sense since this object is declared as the base class type). Why is this? It's because it's a reference type.

You don't believe me. Run your code in debug mode and mouse over the variable that was assigned the cast object (base class type). Reflection will show you it's the derived class, even though you just casted it to a base class.

What does this mean? You can't use XMLInclude and you can't cast the derived class object to work with the webservice method.

Solution:

You need to create a new instance of the base class object and copy all the properities manually (in code) from the derived class object. I put this in a method (e.g. BaseClass DerivedClass.ToBaseClass())

I wish there was a better way. If you have access to the base class and it can see the derived class definition. All you have to do is use XMLInclude to include the derived class type.

See XmlInclude - Not Quite as Useless as I Thought

Tuesday, April 21, 2009

Converting One Array Type to Another - Hacking with Lambda

Started with this:

private ResponseListing[] PopulateListings
(ListingFindResult[] listings)
{
List newListings = new List();
ResponseListing newListing;

foreach (ListingFindResult listing in listings)
{
newListing = new ResponseListing(listing);
newListings.Add(newListing);
}
return newListings.ToArray();
}


Hacked to this:

private ResponseListing[] PopulateListings
(ListingFindResult[] listings)
{
return Array.ConvertAll(listings, delegate
(ListingServiceProxy.ListingFindResult d)
{ return new ResponseListing(d); });
}


Final hack with lambda function:

return Array.ConvertAll(listings, d => new ResponseListing(d));

For generic list you can do the following:

List<Pnts> myPoints = GetListOfMyPoints();

List<Point> yourPoints = myPoints.ConvertAll<Point>(p => new Point(p));

Note: the constructor of Point has to be able to take and translate Pnts object







public static TOutput[] ConvertAll(TInput[] array, Converter converter);

string[] sa2 = Array.ConvertAll(data, delegate(double d) { return d.ToString(); });

string[] lambdaSA = Array.ConvertAll(data, d => d.ToString());

Credit goes to Patrick Steele's Blog Loops, Conversions and Lambdas and MSDN Array.ConvertAll

Sunday, April 19, 2009

Enum, LINQ, and Lookup Tables in C#/SQL Server

Three options:

1. Auto generate ENUM from a lookup table (still have to compile). Here's some helpful links:

2. Just use a dataset object directly (but is a bit ambiguous when coding).

3. Use something that implements IDictionary. This is not as nice as an Enum, but you get the dynamic benefit and it's not as ambiguous when you code. Here's an example:

//put this in a static class, singleton, abstract class, or whatever fits your need

private SortedList _CriteriaItem;

//get data from database and iterate over the dataset to populate the list
public void Add(object Key, object Value)
{
_CriteriaItem.Add(Key, Value);
}

public String GetDescriptionByCode(String key)
{
if (_Item.ContainsKey(key))
{
return _Item[key].ToString();
}

return "";
}


public String GetCodeByDescriptionBy(String description)
{
if (_Item.ContainsValue(description))
{
foreach (String key in _Item.Keys)
{
if (_Item[key].ToString() == description)
{
return key.ToString();
}
}
}

return "";
}

Enum Databinding to DropDownList in C#

//Enumerator
public enum Month
{
Jan = 1,
Feb = 2,
Mar = 3,
Apr = 4,
May = 5,
Jun = 6,
Jul = 7,
Aug = 8,
Sep = 9,
Oct = 10,
Nov = 11,
Dec = 12
}

//Databinding enum text values
ddlMonth.DataSource = Enum.GetNames(typeof(Month));

//Assigning enum text value to a databound object
ddlMonth.SelectedValue = ((Month)object.Date.Value.Month).ToString();