csharp etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
csharp etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

10 Eylül 2012 Pazartesi

code-first wants to recreate the database although the backing model is not changed

When the database is in use in production, you do not have the chance of losing data anymore.. Even though i did not make any changes in the data model, code first wanted to recreate the database by throwing an error message such as

The model backing the 'mycontext' context has changed since the database was created. Consider using Code First Migrations to update the database.

My problem is pretty much the same : http://stackoverflow.com/questions/10254613/mvc3-and-code-first-migrations
" In short, even if Db-s are the same migration table data might not be - and hash comparison may fail."
And luckily, the solution in the link worked for me..
I examined the migration difference by running the following command in package manager:

Update-Database -Script

.. and solved the problem by finding the  INSERT INTO [__MigrationHistory] ...  statement and executing it on ms sql server..


This workaround part of this answer explains the cause of the error: http://stackoverflow.com/questions/9516341/code-first-dbmigrator-causes-error-when-building-from-different-machines/11398366#11398366
According to the answer, the naming of association tables appears to be of an indeterminate order in EF causing the above error.



29 Ağustos 2012 Çarşamba

using toString() without doing null check

Checking for null each time before calling toString() for an object is annoying, especially while logging..
Here is the solution: 

string.Format("{0}", myObj); 
displays an empty string for null object, otherwise calls toString()..

28 Ağustos 2012 Salı

generate toString() automatically in Visual Studio

I am looking for a way to override toString() methods of my beans as i did in Eclipse..
here is a discussion about it: http://stackoverflow.com/questions/4932136/is-there-a-tostring-generator-available-in-visual-studio-2010

Pressing a dot, selecting override and toString() generates something like that:


public override string  ToString()
{
  return base.ToString();
}


However, what i want is a long string which is a concatanation of the bean's attributes.. I do not want to use reflection because of performance issues.. So, the solution is installing Autocode 4.0 http://visualstudiogallery.msdn.microsoft.com/48eeb43f-cb46-4680-b7df-11e73cf894ca
http://www.devprojects.net/download

After installation (which is running the downloaded .msi file), just press ctrl + enter to see the Autocode window in Visual Studio.. ( http://www.devprojects.net/blog/article/start-using-autocode )



Select tostr in the window and the following code will be genarated automatically:



override public string ToString()
        {
            string str = String.Empty;
            str = String.Concat(str, "ID = ", ID, "\r\n");
            str = String.Concat(str, "EskiID = ", EskiID, "\r\n");
            str = String.Concat(str, "Aktif = ", Aktif, "\r\n");
            str = String.Concat(str, "VersiyonSayisi = ", VersiyonSayisi, "\r\n");
            str = String.Concat(str, "Tanimi = ", Tanimi, "\r\n");
            return str;
        }



26 Ağustos 2012 Pazar

using description for enums while filling combobox

My ongoing project has a strict deadline, so we have to deliver it on time, we have no other chance..
Fortunately (or maybe unfortunately) we do not have to deliver the whole functionality at once.We deliver pieces of software gradually..
During development, i note down what to post, and i do post when i have time.. This is one of them..

writing enum descriptions:
public enum DescriptionType
    {
        [Description("Adres Türü")]
        AddressType= 1,
        [Description("Puan Türü")]
        ScoreType = 2,
        [Description("Arşiv Türü")]
        ArchiveType= 3,
...


// where the combobox is initially loaded (for me formLoad)
 this.comboDescriptionType.DataSource = Enum.GetValues(typeof( DescriptionType ));

// add this to combobox format event
 private void comboDescriptionType _Format(object sender, ListControlConvertEventArgs e)
        {
            try
            {
                 DescriptionType desc= ( DescriptionType )e.ListItem;
                e.Value = GetDescription(desc);
            }
            catch (Exception ex)
            {
                // No index selected.
            }
        }

     public static string GetDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
                  (DescriptionAttribute[])fi.GetCustomAttributes(
                  typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }



3 Ağustos 2012 Cuma

a few newbie tips (WinForms)

In this post, i shared a few tips which i noted down during my first experience with WinForms.

1st Tip:
populating a combobox with enum :

           this.comboBox.Items.AddRange(Enum.GetNames(typeof(MyEnumType)));


populating a combobox with collection:


            List sentenceList = server.retrieveSentences();
            this.comboBoxSentences.DataSource =  sentenceList  ;
            this.comboBox Sentences .DisplayMember = "SentenceCode";
            this.comboBox Sentences .ValueMember = "ID";

http://stackoverflow.com/questions/2417960/populating-a-combobox-using-c-sharp

2nd Tip:
the error message:

Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

http://stackoverflow.com/questions/5532810/entity-framework-code-first-defining-relationships-keys
In my case, the problem was due to cascading deletions. Entity A includes a list of Entity B. And Entity S both includes Entity A and Entity B. In order to resolve it, i disabled cascade delete convention.

              modelBuilder.Conventions.Remove(<OneToManyCascadeDeleteConvention>);  


3rd Tip:
several LINQ samples here: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b/viewsamplepack

4th Tip:
TreeView example:
         // the selected sentence in the sentence tree

         public Sentence selectedSentence;

         // fills treeview with sentence list retrieved from database
         private void fillTreeView()
        {
            // retrive sentences from database
            List sentenceList = server.retrieveSentences();
         
            // this dictionary holds tree nodes. The key is the id of sentence.
            Dictionary treeNodeDict<int, TreeNode &gt = new Dictionary(<int, TreeNode >);

            // the root sentence of the tree
            Sentence root = findRootNode( sentenceList  );
           
            // root sentence is turned into a tree node.
            TreeNode rootNode = this.treeView.Nodes.Add( root.Summary);
            rootNode.Name = root.ID.ToString();
            treeNodeDict.Add(root.ID, rootNode);

            // main loop for constructing the treeview
            foreach (var sentence in  sentenceList  )
            {
                TreeNode parent;
               
                // if dictionary contains the sentence, this means that sentence has been already
                // converted to a tree node, so use it
                if (treeNodeDict.ContainsKey( sentence  .ID))
                {
                    parent = treeNodeDict[ sentence  .ID];
                }
                 // if dictionary does not contain the sentence, create a new tree node and
                 // add to dictionary for later reuse.
                else
                {
                    parent = new TreeNode( sentence.Summar );
                    parent.Name =  sentence   .ID.ToString();
                    treeNodeDict.Add( sentence   .ID, parent);
                }

                // the inner loop is to find the children of the parent node (the node in the main loop)
                foreach (var child in  sentenceList)
                {
                    // skip non-children nodes.
                    if (child.ParentSentenceID !=sentence.ID) continue;

                    TreeNode childNode;

                    if (treeNodeDict.ContainsKey(child.ID))
                    {
                        childNode = treeNodeDict[child.ID];
                    }
                    else
                    {
                        childNode = new TreeNode(child.Summary);
                        childNode.Name = child.ID.ToString();
                        treeNodeDict.Add(child.ID, childNode);
                    }

                    parent.Nodes.Add(childNode);
                }
            }
        }

        // finds root node of the list. root node is the node with no parent.
        private Sentence findRootNode(List sentenceList)
        {
            foreach (var sentence in  sentenceList )
            {
                if (sentence.ParentSentenceID == null || sentence.ParentSentenceID == 0) return sentence;
            }

            return null;
        }

        // the following methods are for turning the color of the selected node to green.
        private void treeView_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (treeView.SelectedNode != null)
                treeView.SelectedNode.ForeColor = Color.Black;
            e.Node.ForeColor = Color.Green;
            // selected sentence in treeviw is highlighted to green
        }

        private void OwnerDrawAll(object sender, DrawTreeNodeEventArgs e)
        {
            if (((e.State & TreeNodeStates.Selected) != 0) && (!treeViewBirim.Focused))
                e.Node.ForeColor = Color.Blue;
            else
                e.DrawDefault = true;
        }

        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView.SelectedNode != null)
            {
                selectedSenetnce = server.retrieveSentenceByID(Int32.Parse(treeView.SelectedNode.Name));
                treeView.Focus();
            }
        }
    }


http://stackoverflow.com/questions/1838807/winforms-treeview-how-to-manually-highlight-node-like-it-was-clicked
http://www.java2s.com/Code/CSharp/GUI-Windows-Form/TreeViewExample.htm
http://www.java2s.com/Code/CSharp/GUI-Windows-Form/TreeViewDataBinding.htm

5th Tip:
Selected tabPage name:
http://stackoverflow.com/questions/3545624/return-selected-tabpage-name

              tab.SelectedTab.Name

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/

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.


29 Haziran 2012 Cuma

get ID of an entity before SaveChanges()

Unfortunately, when using automatically generated ID s in database, it is not possible to get the ID before doing SaveChanges().

http://stackoverflow.com/questions/6029711/id-of-newly-added-entity-before-savechanges/6029864#6029864

how to write content of dictionary to file

In order to write the content of a dictionary to a file:


        public static void writeDictToFile(Dictionary dict, string filename) {
            File.WriteAllLines(filename + ".txt",
            dict.Select(x => "[" + x.Key + " " + x.Value + "]").ToArray());
        }

http://stackoverflow.com/questions/3067282/how-to-write-the-content-of-a-dictionary-to-a-text-file

25 Haziran 2012 Pazartesi

error : The underlying connection was closed: The connection was closed unexpectedly.

If the error
{"The underlying connection was closed: The connection was closed unexpectedly."}
blows up for some of the web service methods, while others work correctly, the reason may be the return objects refer to each other in a recursive manner. 
In my condition, i got the error while returning Sentence.
Paragraph() {
     List<Sentence> Sentence;
}
Sentence() {
  List<Paragraph> SomeText;
}
When the type of SomeText is changed from Paragraph  to Sentence, everything works fine!

error: LINQ to Entities does not recognize the method ...Last

The complete error message is as follows :


{"LINQ to Entities does not recognize the method 'Core.Sentence Last[Sentence (System.Collections.Generic.IEnumerable`1[Core.Sentence])' method, and this method cannot be translated into a store expression."}

and the causing line is:


retList = (dal.Paragraph.Include("Sentence").Where(p => p.Sentence.Last().Topic.ID == topic.ID)).ToList();

This is because Last and LastOrDefault are just not supported by the LINQ to SQL query translator.
http://forums.asp.net/t/1480557.aspx/1

The solution is ordering Sentence in descending order and use FirstOrDefault instead of Last:

 retList = (dal.Paragraph.Include("Sentence").Where(p => p.Sentence.OrderByDescending(s => s.ID).FirstOrDefault().Topic.ID == topic.ID)).ToList();


codefirst inheritance strategies

I am in the .net world  for a while and bumped into several technical problems so far. I plan to post the problems with their solutions when i have time for this. I also want to write a post comparing .net and java platforms. For now, it is enough to state that i am a java fan..

http://romiller.com/2010/09/29/ef-ctp4-tips-tricks-code-first-inheritance-mapping/  is an article about how codefirst handles inheritance during table generation. To sum up, default table generation strategy is Table-per-Hierarchy (TPH) which keeps all data in one table created for the base type and automatically creates a Discriminator field in order ro discriminate different types. Table-per-Type (TPT) creates a table for the base type with shared columns and different tables for each derived type whereas Table-per-Concrete Class(TPC) creates an entirely different table for each class.. However, when the table generation strategy is modified, previously working code may start to blow up.. Moreover, performance is best when the default strategy (TPH) is used: http://blogs.msdn.com/b/adonet/archive/2010/08/17/performance-considerations-when-using-tpt-table-per-type-inheritance-in-the-entity-framework.aspx

7 Şubat 2011 Pazartesi

a C# starter..

I am given a component written in C#, and i need to re-model it as a set of web services in order to integrate it with some other java components..
This is my first contact with .net world, so i need to be encouraged :)

http://www.csharpnedir.com/articles/read/?filter=&author=&cat=&id=49&title=C
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=35
http://www.java2s.com/Tutorial/CSharp/CatalogCSharp.htm
http://www.csharp-station.com/Tutorial.aspx