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

Wednesday, May 28, 2014

Add ID value for non-auto-increament field under Entity Framework

If you use an “ID” field in your entity, & this “ID” field is not auto-increament, Entity Framework will fail when generate insert sql.

Solve:

Add a DatabaseGeneratedAttribute to this “ID” field, with DatabaseGeneratedOption.None option, like this:

public abstract class BaseAccount{    [Key]    [DatabaseGenerated(DatabaseGeneratedOption.None)]    public int ID { get; set; }    ......}

Successfully solved under Entity Framework 4-6.

Entity Framework 6.0 MigrationHistory table on SQLite

The following SQL is used to create __MigrationHistory table in SQLite database for Entity Framework 6.0 in Code-First mode.

CREATE TABLE [__MigrationHistory] ([MigrationId] CHAR NOT NULL, [Model] BLOB NOT NULL, [ContextKey] CHAR NOT NULL, [ProductVersion] CHAR NOT NULL, CONSTRAINT [sqlite_autoindex___MigrationHistory_1] PRIMARY KEY ([MigrationId]));

 

Sunday, October 13, 2013

Instantiate particular class based on object value

I have classes for each payment mode for e.g. Cash, Cheque, Card. I have to pass object as a parameter based on object value I have to instantiate a relevant class.

How can I achieve this? Suggest me a better design

public interface CollectionInfo {    //Code Goes here}public class Cash implements CollectionInfo {    //Code goes here}public class CollectionFactory {    public void newInstance(Enum<CollectionMode> collectionMode) {    }}public interface Receipts {    public Receipt createReceipt(String Amount, /*(Here i need to pass parameter of object either cash ,Cheque or card),*/Date date);}

You could pass an enumeration (Cash/Cheque/Card) into a factory ?

e.g.

Payment p = PaymentFactory.newInstance(PaymentMode.Cash);

and within that method you would do:

switch(mode) {   case PaymentMode.Cash:      return new CashPayment();   // ...}

where CashPayment, ChequePayment etc. are subclasses of Payment.

Wednesday, October 9, 2013

Linq to object Right outer join

I have written following linq query yet I am not getting expected result.My Expected result is all the matching record bettween lst & list & all the non matching record from list
for example.

I want following result

a,b,c,d,e,f

public class Com : IEqualityComparer<DuplicateData>    {        public bool Equals(DuplicateData x, DuplicateData y)        {            return x.address.Equals(y.address);        }        public int GetHashCode(DuplicateData obj)        {            return obj.address.GetHashCode();        }    }static void Run (){    List<string> lst = new List<string>();    lst.Add("a");    lst.Add("b");    lst.Add("c");    lst.Add("p");    List<DuplicateData> list = new List<DuplicateData>()    {        new DuplicateData{address="a"},        new DuplicateData{address="a"},        new DuplicateData{address="a"},        new DuplicateData{address="b"},        new DuplicateData{address="b"},        new DuplicateData{address="c"},        new DuplicateData{address="d"},        new DuplicateData{address="e"},        new DuplicateData{address="f"},    };    var dup = list.Distinct(new Com());    var RightJoin = from x in dup                    join y in lst                    on x.address equals y                    into right                    from z in right                    select new                    {                        UniqueAddress = z,                    };}

Try it like this:

var RightJoin = from x in dup                join y in lst                on x.address equals y                into right                from z in right.DefaultIfEmpty(x.address)                select new                {                    UniqueAddress = z,                };

result is (a,b,c,d,e,f)

Working sample: http://ideone.com/MOIhZH


Explanation

To make a left/right join in linq you have to use DefaultIfEmpty method, that will yield (default) result when there is no match (the joined result is empty). However, default value for string is null so you have to provide default value from the “left side” collection to see it in the result set.


Alternative approach

This is probably more convenient approach. Instead of selecting from z & providing the default value, you will select from x.address – the left side of the join.

var RightJoin = from x in dup                join y in lst                on x.address equals y                into right                from z in right.DefaultIfEmpty()                select new                {                    UniqueAddress = x.address,                };

Friday, October 4, 2013

use parentheses in c# calculator

Hello I just write a simple calculator in C# & I want to improve my program to handle parentheses.

Here is my button to add 1(digit):

 private void btnOne_Click(object sender, EventArgs e)        {            txtResult.Text += '1';        }

This is a method for my Plus button:

private void btnPlus_Click(object sender, EventArgs e)        {            lblChar.Text = "+";            num1 = float.Parse(txtResult.Text);            txtResult.Text = "";        }

And this is for to calculate final result:

private void btnEqual_Click(object sender, EventArgs e)        {    num2 = float.Parse(txtResult.Text);                if (lblChar.Text == "+")                {                    num3 = num1 + num2;                    txtResult.Text = Convert.ToString(num3);                }}

Anyone can assist me to write parentheses for my program?

You can use NCalc – Mathematical Expressions Evaluator for .NET

 Expression e = new Expression("2 + (3 + 5)*6"); var result = e.Evaluate();

Thursday, October 3, 2013

C# Get generic non-array type from generic array type

Given the following function;

void SomeFunction<T>(...){    SomeOtherFunction<T>();}

This works fine, yet sometimes the function fails before T passed is an array type, yet it mustn’t be an array type. These functions have to do with JSON deserialization of a dictionary, yet for some reason it doesn’t accept the T array argument when the dictionary has only one entry.

In short, I want to do this

void SomeFunction<T>(...){    try {    SomeOtherFunction<T>();    } catch ( Exception e ){        SomeOtherFunction<T arrayless>();    }}

I’ve tried a ton of stuff, & I realize the real problem is somewhere else, yet I need to temporary fix this so I can work on a real solution in the deserializer. I tried reflection too using the following method;

MethodInfo method = typeof(JToken).GetMethod("ToObject", System.Type.EmptyTypes);MethodInfo generic = method.MakeGenericMethod(typeof(T).GetElementType().GetGenericTypeDefinition());object result = generic.Invoke(valueToken, null);

But that doesn’t quite work either.

Thank you!

I am not really sure what you are trying to achieve here, yet to obtain the type of the elements in an array, you have to use Type.GetElementType():

void SomeFunction<T>(){    var type = typeof(T);    if(type.IsArray)    {        var elementType = type.GetElementType();        var method = typeof(Foo).GetMethod("SomeOtherFunction")                                .MakeGenericMethod(elementType);        // invoke method    }    else        foo.SomeOtherFunction<T>(...);}

Wednesday, July 18, 2012

Setup visual style for WPF applications

Maybe you’re facing the same problem with me: WPF applications cannot use Windows Visual Style by default.
If you want a solution, follow these steps:

  1. Download this & unpack: Link.
  2. Add the “application.manifest” file to your wpf project in VisualStudio.
  3. Right click on the project in “Solution Explorer”, select “Properties”.
  4. Choose “Application” tab, in the “Resource” groupbox, select “Icon & manifest”, then select “application.manifest” on manifest combobox.
  5. Save all & build application, run it!

 

Sunday, February 26, 2012

Attributes related to WinForms Designer

  1. BrowsableAttribute
    This attribute tells designer, whether the associated property should be displayed.
  2. DefaultEventAttribute
    This attribute tells designer, if double clicked a component, which event it should generate code for.
  3. DefaultValueAttribute
    This attribute indicates the default value for the property. If you donate a value not equals default value, it will be displayed in bold.
  4. DesignerCategoryAttribute
    This attribute tells designer it belongs to what category.
  5. DesignerSerializationVisibilityAttribute
    This attribute tells designer how to serialize the associated property.
  6. DesignTimeVisibleAttribute
    This attribute tells designer whether the component should be displayed in toolbox.

To be continued…

Thursday, February 23, 2012

How to use default parameter in C# 2.0 & 3.5

For example, I need a method like this:

public void InitData(int index, object value, bool required = false) {}

I can write it as:

using System.Runtime.InteropServices;public void InitData(int index, object value, [Optional, DefaultParameterValue(false)] bool required) {}

The attribute Optional tells compiler that the parameter required has default value. And the attribute DefaultParameterValue(false) tells compiler what is the default value.

Very simple. Isn’t it?

Sunday, January 29, 2012

WPF in action: Dynamically set style for control

For example, I have a xaml like this:

<TabItem Header="Tab1" Style="{DynamicResource TabItemWithButton}">

I want create a new tab dynamically, & set style to “TabItemWithButton”, I will use this code:

newTab.SetResourceReference( TabItem.StyleProperty, "TabItemWithButton" );

Simple!

Actually, you can use SetResourceReference method to set many dependency properties, explore it!

Thursday, August 11, 2011

.Net Assembly Redirection

Sometimes, we need redirect an assembly to a different version, we can do it like this:

<?xml version="1.0" encoding="utf-8" ?><configuration>    <runtime>        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">            <probing privatePath="libs"/>            <dependentAssembly>                <assemblyIdentity name="MathLibrary"                    publicKeyToken="8210BDCE54DAB3C2"/>                <bindingRedirect oldVersion="1.1.1.1"                    newVersion="1.1.2.2"/>            </dependentAssembly>        </assemblyBinding>    </runtime></configuration>

 

In element “probing, “privatePath” is additional seraching path for assemblies.

In element “assemblyIdentity“, “name” is the assmebly you want to redirect, “publicKeyToken” is its public key. So the assembly must be strong-named to make a redirection.

After set the assembly, you can make your redirection. In element “bindingRedirect“, use “oldVersion” & “newVersion” to redirect it.