26 Temmuz 2012 Perşembe

access to main form from child fom (WinForms)

Assume ChildForm is opened from MainForm:


ChildForm form= new  ChildForm  ();
form.ShowDalog(this);


Now, to access MainForm from ChildForm (to refresh something on MainForm etc.), call this from child form:


MainForm parent = ( MainForm  )this.Owner;
// do sonething in parent form
this.Close(); // close child form



http://stackoverflow.com/questions/5443932/accessing-main-form-from-child-form

update error in dbcontext (ef)

When i tried to update an entity by using DbContext (entity framework), i got this error:

{"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."}

The discussion in http://stackoverflow.com/questions/6033638/an-object-with-the-same-key-already-exists-in-the-objectstatemanager-the-object helped me to solve it.
I replaced the lines


//context.Sentence.Attach(temp);
// context .Entry(temp).State = System.Data.EntityState.Modified;


with the following:


Sentence old =  context.Sentence.Find(temp.ID);
context .Entry(old).CurrentValues.SetValues(temp);

12 Temmuz 2012 Perşembe

reading an excel file in C#

In order to read an excel file cell by cell, the first step is adding Microsoft Excel Object Library as a reference to the project (http://www.c-sharpcorner.com/Forums/Thread/80161/). 
Afterwards, the following code should work:

// ..
using Excel = Microsoft.Office.Interop.Excel;
// ...

 private static void ReadExcelFile()
 {
            Excel.Application exApp ;
            Excel.Workbook exWorkBook ;
            Excel.Worksheet exWorkSheet ;
            Excel.Range range ;


            string str;
            int row = 0;
            int column = 0;


            String pwd =  Directory.GetCurrentDirectory();


            exApp = new Excel.Application();
            exWorkBook = exApp.Workbooks.Open("C:/filename.xls" );
            exWorkSheet = (Excel.Worksheet)exWorkBook.Worksheets.get_Item(1);


            range = exWorkSheet.UsedRange;


            for ( row  = 1;  row  <= range.Rows.Count; row++)
            {
                for ( column = 1;  column <= range.Columns.Count;  column  ++)
                {
                    // to allow nullable cells
                    if (range.Cells[rCnt, cCnt].Value2 == null) continue;
                    str = range.Cells[row,  column].Value2.ToString();
                }
            }


            exWorkBook.Close(true, null, null);
            exApp.Quit();
}


see these for more:
http://csharp.net-informations.com/excel/csharp-read-excel.htm
http://dontbreakthebuild.com/2011/01/30/excel-and-c-interop-with-net-4-how-to-read-data-from-excel/

11 Temmuz 2012 Çarşamba

JPA tips 2


A previous post about this topic: http://hilaltarakci.blogspot.com/2011/03/jpa-tips.html

Actually, long version of this post includes notes taken while i was reading Chapter 9- Working with Objects of book Java Persistence with Hibernate (http://www.manning.com/bauer2/). However, i could not post it because of the copyright rules..

 But at least, i can recommend to buy the book and read the whole chapter..

free data models

I am trying to model a complex questionnaire and during my googling for best practices i discovered this website: http://www.databaseanswers.org/data_models/
An excellent site full of free and well prepared data models on several topics..

10 Temmuz 2012 Salı

free manual search engine

Discovering beneficial manuals, especially when newbie to a topic, technology etc.,  is vital.
 http://the-manuals.com/ seems to retrieve good documentation..

9 Temmuz 2012 Pazartesi

LINQ error: Null value for non-nullable member.

When i tried to save an object with a complex type (with a null instance of the complex type), i got the following error:

{"Null value for non-nullable member. Member: 'Sentence'."}

In this link there is an explanation for this: http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/50d33271-c8e3-468f-82e1-7c3178cb4322/
According to the explanation, complex types are always considered as required in entity framework. My workaround is creating an instance of the complex type with new keyword in the constructor.

5 Temmuz 2012 Perşembe

error during migration (update-database, codefirst)

I got the following error when i run Update-Database command in Package Manager Console of Visual Studio:


PM> update-database
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
   --- End of inner exception stack trace ---
   at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
Exception has been thrown by the target of an invocation.


The solution is specifying the startup project (http://stackoverflow.com/questions/9174116/entity-framework-4-3-migration-exception-when-update-database):


Update-Database –ProjectName "MyInnerProject" –Force -ConnectionString "Data Source=.;Initial Catalog=initialcatalogname;Persist Security Info=True;User ID=userid;Password=password" -ConnectionProviderName "System.Data.SqlClient" -verbose -StartupProjectName "MyStartupProject"

enum support in entity framework

Enumeration support comes with Entity Framework 5, so for prior versions we need a workaround..
I think the workaround in http://dotnetdevdude.com/Blog/2012/01/09/EntityFrameworkCodeFirstEnum.aspx is suitable.  To apply the workaround:
1.   Create two members for the field you want to use as enum type. In the below example,   SentencePart   is an enumaration which specifies parts of a sentence. SentencePartInt  holds an integer value whereas SentencePartEnum  is the member which is going to be used and processed in the code.
       
        public Nullable SentencePartInt{ get; set; }
        public Nullable< SentencePart> SentencePartEnum
        {
            get { return ( SentencePart) SentencePartInt ; }
            set {  SentencePartInt = (int)value; }
        }
       

2.   Tell the database context not  to persist the enum member.
       modelBuilder.Entity().Ignore(x => x. SentencePartEnum );
3.    Use the enum member in the code, not the integer.


4 Temmuz 2012 Çarşamba

pdf to word converter

When there is a time limit for composing a tutorial for something, a good pdf to word converter tool is a life saver. 14-day trial downloaded from http://www.pdftoword.com/ worked for me..
http://www.pdfonline.com/pdf-to-word-converter/ took a while to convert the pdf online and only converted the document partially because of its size..

2 Temmuz 2012 Pazartesi

clean code

While looking for coding best practices, i discovered this book: http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882 . It is very easy to read with funny drawings..
The guidelines in  http://csharpguidelines.codeplex.com/ are worth sharing as well..