26 Aralık 2012 Çarşamba

easy login mechanism for demo purposes

When you need to prepare a quick demo for a few users and you have not implemented your login mechanism yet, you can easily add forms authentication to you asp.net web application.

a simple login form (.aspx file)
<p>
        <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label>
        <asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox>
    </p>
    <p>
        <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
        <asp:TextBox ID="Password" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
    </p>

server side (aspx.cs file):
         protected void Page_Load(object sender, EventArgs e)
        {
            if (FormsAuthentication.Authenticate(this.UserName.Text, this.Password.Text))
            {
                FormsAuthentication.RedirectFromLoginPage(this.UserName.Text, true);
            }
        }

add the following lines to web.config file:
     <authentication mode="Forms">
      <forms loginUrl="~/menu/Login.aspx"  defaultUrl="~/menu/MenuMyApp.aspx" timeout="2880" cookieless="AutoDetect">
        <credentials passwordFormat="Clear">
          <user name="demo1" password="1"/>
          <user name="demo2" password="2"/>
        </credentials>
      </forms>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>

Your demo app is secure now.. Demo users can only login with the credentials specified.



15 Aralık 2012 Cumartesi

how to telerik:RadMenu show path


In order to view the selected path from your telerik RadMenu as in the picture below, you can use the following code:







aspx code:


<telerik:RadSiteMap ID="BreadCrumbSiteMap" runat="server" DataTextField="Text" DataNavigateUrlField="NavigateUrl">
        <DefaultLevelSettings ListLayout-RepeatDirection="Horizontal" SeparatorText="/" Layout="Flow" />
</telerik:RadSiteMap>



csharp code:


      protected void Page_Load(object sender, EventArgs e)
        {
            RadMenuItem currentItem = RadMenu.FindItemByUrl(Request.Url.PathAndQuery);
            if (currentItem != null)
            {
                currentItem.HighlightPath();
                DataBindBreadCrumbSiteMap(currentItem);
            }
            else
                RadMenu.Items[0].HighlightPath();
        }

        private void DataBindBreadCrumbSiteMap(RadMenuItem currentItem)
        {
            List breadCrumbPath = new List();
            while (currentItem != null)
            {
                breadCrumbPath.Insert(0, currentItem);
                currentItem = currentItem.Owner as RadMenuItem;
            }
            BreadCrumbSiteMap.DataSource = breadCrumbPath;
            BreadCrumbSiteMap.DataBind();
        }



The solution is from here: http://demos.telerik.com/aspnet-ajax/menu/examples/programming/showpath/defaultcs.aspx?Page=Blogs

13 Aralık 2012 Perşembe

using Telerik Scheduler to view weekly lesson plan


In this post, i present the code that configures Telerik radscheduler to view a weekly lesson plan. In order to do this, the selected date attribute should be a month starting at Monday (which is the first week day in the scheduler.)
.aspx code (actually i use it as a user control )
<telerik:RadScheduler runat="server" ID="RadScheduler" Width="750px" SelectedView="WeekView"
    TimeZoneOffset="00:00:00" SelectedDate="2013-04-01" DayStartTime="07:00:00" DayEndTime="23:59:00"
     ReadOnly="true"
     DataEndField="End" 
     DataKeyField="DersProgramiID" DataStartField="Start" DataSubjectField="DersItem" 
     AllowDelete="False" AllowEdit="False" AllowInsert="False" 
     DayView-DayStartTime="07:00:00" DayView-DayEndTime="23:59:00" LastDayOfWeek="Sunday" 
     WeekView-DayEndTime="23:59:00" WeekView-DayStartTime="07:00:00" WeekView-WorkDayEndTime="23:59:00" 
     WeekView-WorkDayStartTime="07:00:00" WorkDayEndTime="23:59:00" WorkDayStartTime="07:00:00" FirstDayOfWeek="Monday" 
     Height="900px" ShowNavigationPane="True" ShowAllDayRow="False" ShowHeader="False" ShowFullTime="False" ShowFooter="False" HoursPanelTimeFormat="HH:mm">
    <TimelineView UserSelectable="false" ShowDateHeaders="false"></TimelineView>
    <TimeSlotContextMenuSettings EnableDefault="true"></TimeSlotContextMenuSettings>
    <AppointmentContextMenuSettings EnableDefault="true"></AppointmentContextMenuSettings>
</telerik:RadScheduler>

csharp code to fill the scheduler:
 public void fill(List list)
 {
      this.RadScheduler.DataSource = list;
      this.RadScheduler.DataBind();

  }

The weekly lesson plan is as follows:

23 Ekim 2012 Salı

introduction to telerik reports

it has been years since i have not dealt with reporting.. so, i am a total newbie for this..
in this post, i share my one-day activity on warming up using telerik reports, a sample telerik report about a specific user's information viewed in a web app and how to deploy it in a remote server..
first thinngs first.. my bookmarks:

Report library part:
Now, the first step is creating a report library project.. Then a telerik report is created. i used the report wizard and used an SqlDataSource as the data source. My select query contains a parameter:
SELECT ...
FROM  ...  
WHERE TableStudent.ID = @StudentID
The report also contains a parameter with the same name. 
The constructor for the report is something like that:
        public ReportStudent(int studentID)
        {
            InitializeComponent();

            this.ReportParameters["StudentID"].Value = studentID;
            this.StudentDataSource.Parameters[0].Value = studentID;
            this.StudentDataSource.SelectCommand =           this.StudentDataSource.SelectCommand.Replace("@StudentID", studentID.ToString());
        }

Web app part:
In the web app which is going to view the report, i added a report viewer from the toolbox, but left the report property unassigned.  In the web page, the user selects a student, then presses a button and the report for the selected student is viewed inside the report viewer.
The button click event code is as follows:
protected void ButtonReport_Click(object sender, EventArgs e)
        {
            if (Session["StudentID"] != null &&
                !(((string)Session["StudentID"]).Trim().Equals("")))
            {
                ReportViewer viewer = (ReportViewer)this.ReportContent.Controls[0];
                ReportStudent report = new ReportStudent(Int32.Parse((string)Session["StudentID"]));
                viewer.Report = report;
                viewer.RefreshReport();
            }
        }

The above scenario works perfectly..
When deploying to the remote server, change the connection strings accoringly in:
  • Web.config of web app
  • Settings.settings and app.config for the report library.
Besides,  add the telerik libraries shown in the figure. (By the way, i am not sure if this list is minimal or not...)










and finally, here is telerik relevant portions of my web.config:



<configuration>
  <configSections>
    <section name="Telerik.Reporting" type="Telerik.Reporting.Processing.Config.ReportingConfigurationSection, Telerik.Reporting, Version=6.0.12.215, Culture=neutral, PublicKeyToken=a9d7983dfcc261be" allowLocation="true" allowDefinition="Everywhere" />
  </configSections>
  <Telerik.Reporting>
    <Extensions>
      <Render>
        <Extension name="IMAGE" visible="false"></Extension>
        <Extension name="HTML" visible="false"></Extension>
        <Extension name="MHTML" visible="false"></Extension>
        <Extension name="XLS" visible="false"></Extension>
        <Extension name="CSV" visible="false"></Extension>
        <Extension name="RTF" visible="false"></Extension>
      </Render>
    </Extensions>
  </Telerik.Reporting>
  ...
  <appSettings>
    <add key="Telerik.Skin" value="Web20" />
    <add key="Telerik.ScriptManager.TelerikCdn" value="Disabled" />
    <add key="Telerik.StyleSheetManager.TelerikCdn" value="Disabled" />
  </appSettings>
  <system.web>
    <pages>
      <controls>
        <add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI" />
      </controls>
    </pages>
    <compilation targetFramework="4.0">
      <assemblies>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Speech, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="Telerik.ReportViewer.WebForms, Version=6.0.12.215, Culture=neutral, PublicKeyToken=A9D7983DFCC261BE" />
        <add assembly="Telerik.Reporting, Version=6.0.12.215, Culture=neutral, PublicKeyToken=A9D7983DFCC261BE" />
      </assemblies>
    </compilation>
    <httpHandlers>
      <add path="ChartImage.axd" verb="*" type="Telerik.Web.UI.ChartHttpHandler"
        validate="false" />
      <add path="Telerik.Web.UI.SpellCheckHandler.axd" verb="*" type="Telerik.Web.UI.SpellCheckHandler"
        validate="false" />
      <add path="Telerik.Web.UI.DialogHandler.aspx" verb="*" type="Telerik.Web.UI.DialogHandler"
        validate="false" />
      <add path="Telerik.RadUploadProgressHandler.ashx" verb="*" type="Telerik.Web.UI.RadUploadProgressHandler"
        validate="false" />
      <add path="Telerik.Web.UI.WebResource.axd" verb="*" type="Telerik.Web.UI.WebResource"
        validate="false" />
      <add path="Telerik.ReportViewer.axd" verb="*" type="Telerik.ReportViewer.WebForms.HttpHandler, Telerik.ReportViewer.WebForms, Version=6.0.12.215, Culture=neutral, PublicKeyToken=a9d7983dfcc261be"
     validate="true" />
    </httpHandlers>
  </system.web>
  <system.webServer>
    <handlers>
      <remove name="ChartImage_axd" />
      <add name="ChartImage_axd" path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" preCondition="integratedMode" />
      <remove name="Telerik_Web_UI_SpellCheckHandler_axd" />
      <add name="Telerik_Web_UI_SpellCheckHandler_axd" path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" preCondition="integratedMode" />
      <remove name="Telerik_Web_UI_DialogHandler_aspx" />
      <add name="Telerik_Web_UI_DialogHandler_aspx" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" preCondition="integratedMode" />
      <remove name="Telerik_RadUploadProgressHandler_ashx" />
      <add name="Telerik_RadUploadProgressHandler_ashx" path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" preCondition="integratedMode" />
      <remove name="Telerik_Web_UI_WebResource_axd" />
      <add name="Telerik_Web_UI_WebResource_axd" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" preCondition="integratedMode" />
      <add name="Telerik.ReportViewer.axd_*" path="Telerik.ReportViewer.axd" verb="*" type="Telerik.ReportViewer.WebForms.HttpHandler, Telerik.ReportViewer.WebForms, Version=6.0.12.215, Culture=neutral, PublicKeyToken=a9d7983dfcc261be" preCondition="integratedMode" />
    </handlers>
  </system.webServer>
</configuration>

18 Eylül 2012 Salı

possible cause for a common AjaxControlToolkit error

The full error message:

Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "AjaxControlToolkit.Properties.Resources.NET4.resources" was correctly embedded or linked into assembly "AjaxControlToolkit" at compile time, or that all the satellite assemblies required are loadable and fully signed.


The working environment is the same as in http://hilaltarakci.blogspot.com/2012/09/using-calendarextender.html.
I have a user control using ajax control toolkit components and i am pretty sure this control works properly on its own. However, when i tried to use the control in another control, i got the above error.
In my case, adding the following lines to the caller user control fixed my problem:



<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>



i got the idea from here: http://www.vijaykodali.com/Blog/post/2011/11/06/Make-sure-AjaxControlToolkitPropertiesResourcesNET4resources-was-correctly-embedded.aspx
it specifies the reason for the error as

AjaxControlToolkit’s control load reference refers to the base System.Web.UI.Control method which is present as a part of the ASP.NET AJAX Libraries and those libraries are referenced only when the ScriptManager is referenced in the page.

using CalendarExtender


here is some useful links to use CalendarExtender
http://www.ezineasp.net/post/AJAX-Control-Toolkit-Calendar-Extender.aspx
http://hazaa.com.au/2007/08/13/how-to-use-the-ajax-control-toolkit-calendar-extender-control/

lets summarize the process:

  • install ajax control toolkit  ( http://ajaxcontroltoolkit.codeplex.com/) to your project via Visual Studio package manager console with command Install-Package AjaxControlToolkit. This creates packages folder in your repository and downloads the assemblies in that folder.. 
  • in your Web.config file add these two statements:
    • <add assembly="AjaxControlToolkit"/> This line goes under configuration->system.web->compilation->assemblies tag.
    • < add tagPrefix= " ajaxToolkit "  assembly= " AjaxControlToolkit "  namespace= " AjaxControlToolkit "  / > This line goes under configuration->system.web->pages->controls tag.
  • use the control as follows:
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix= " cc1" %>

<asp:TextBox ID="TextBoxDogumTarihi" runat="server"/>
<asp:Image ID="ImageDogumTarihi" runat="server" ImageUrl="../images/calendar.png" />
<cc1:CalendarExtender ID="CalendarDogumTarihi" TargetControlID="TextBoxDogumTarihi" runat="server"
                                        PopupPosition="Right"   PopupButtonID="ImageDogumTarihi"   />

In the following image, the above is a CalendarExtender whereas the below is a styled asp.net calendar.


 to customize CalendarExtender see http://www.ezineasp.net/post/Customized-AJAX-Calendar-Control-CSS-Example.aspx

10 Eylül 2012 Pazartesi

mssql - how to remove null constraint

i spent almost 5 hours for removing a null constraint this evening !!!
here is how to do so:

to view constraints on a table: (http://bytes.com/topic/sql-server/answers/710346-how-do-i-view-table-information-such-constraints)

EXEC sp_help  ThisIsMyTable


to drop a constraint:

ALTER TABLE [ThisIsMyTable] DROP CONSTRAINT [ConstraintName]


to make a non-nullable field nullable: (http://stackoverflow.com/questions/3370159/how-to-remove-not-null-constraint-in-sql-server-using-query)

ALTER TABLE  ThisIsMyTable ALTER COLUMN ThisIsTheColumn int NULL

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.



30 Ağustos 2012 Perşembe

to see all running tasks on windows

to see all running tasks on windows :

TASKLIST /v /fi "STATUS eq running"

for more: http://ss64.com/nt/tasklist.html

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/

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..

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

27 Haziran 2012 Çarşamba

html vertical line

Unfortunately, there is no explicit element in html in order to draw a vertical line .. However, there are 3 ways to achieve this:
<td width="5%"style="border-left: 1px solid black; padding: 5px;">   </td>
2) With 1-pixel image
3) With css (div) 


Another option is to draw very thick and short horizontal line: http://forum.yola.com/yola/topics/vertical_lines_using_html

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

29 Mayıs 2012 Salı

trac on windows

Trac (http://trac.edgewall.org/) is my favorite issue tracking tool. However, installing trac on windows is not a straightforward task. The easiest way to achieve this is by using bitnami.. .http://bitnami.org/download/files/stacks/trac/0.12.3-0/bitnami-trac-0.12.3-0-windows-installer.exe
Just run the exe, specify a port for trac, specify a project name and enjoy yourself..

22 Nisan 2012 Pazar

two useful online tools

an online free tool for merging multiple pdf files into one: http://foxyutils.com/mergepdf/

an online image conversion tool: http://www.go2convert.com/

8 Nisan 2012 Pazar

numbered list in Latex

Here is a way of creating numbered lists in Latex:



\begin{enumerate}
\item bla
\begin{enumerate}
\item bla bla
\item bla bla bla
\end{enumerate}
\item bla bla bla bla
\item bla bla bla bla bla 
\end{enumerate}

26 Mart 2012 Pazartesi

from word to wiki

In order to publish word document content as wiki page, follow these steps:

  1. Save word document as html.
  2. Copy the source html and use the tool on  http://toolserver.org/~diberri/cgi-bin/html2wiki/index.cgi to convert raw html to mediaWiki.
  3. Finally, copy the mediaWiki content to your wiki page.
Unfortunately, i had problem with toc (table of contents) part and had to modify the page manually..

22 Ocak 2012 Pazar

Latex error: Unknown graphics extention: .eps

While trying to output a pdf from a .tex file including an .eps image, i got the error "Unknown graphics extention: .eps", even though including the graphics package..
Following this discussion http://www.latex-community.org/forum/viewtopic.php?f=31&t=84&sid=770badff71c4ad41aae498dbfad6c058&start=10, someone states that:

Remember, EPS only works with the following compiling routes:
LaTeX => DVI
LaTeX => PS
LaTeX => PS => PDF


but not with LaTeX => PDF !!!




So, i tried Texify instead of PDFTexify in WinEdt with success.. Afterwards, i converted the output to PDF with dvi2pdf as in the figure:

16 Ocak 2012 Pazartesi

pygraphviz on windows (Python 2.7)

Installing pygraphviz on Windows is a lit bit tricky.. It took almost all my sunday afternoon to find out a solution that works for me.. Finally i did by following instructions on http://blog.ropardo.ro/2011/11/28/installing-pygraphviz-on-windows/ 


Here is my steps:
  1. Install ActivePython Community Edition (http://www.activestate.com/activepython) in order to have easy_install. Add PYTHON_HOME/Scripts folder to PATH variable.
  2. Install required/wanted Python packages with easy_install. However, pygraphviz do not have a Windows build, and it can not be easy installed, since Python does not know where Graphviz is installed..
  3. Install Graphviz (http://www.graphviz.org/
  4. Installed an old version of MinGW (specifically the build on 20100831) (http://www.mingw.org/) . Add MinGW/bin to PATH.
  5. Download pygraphviz (http://networkx.lanl.gov/pygraphviz/) and extract it.
    1. Edit setup.py of pygraphviz as follows:     (they are None as default..)
      • library_path="C:/Graphviz 2.28/lib/release/lib"
      • include_path="C:/Graphviz 2.28/include/graphviz" 
    2. Modify line 285 (most probably) from “C:\python27\lib\distutils\unixcompiler.py" as follows:
      • old:  compiler = os.path.basename(sysconfig.get_config_var("CC"))
      • new: compiler =  "gcc" 
    3. Run the following command from pygraphviz-$version folder:
      • python setup.py build -c mingw32
    4. Copy the pygraphviz folder under (some place like) C:\pygraphviz-1.1\build\lib.win32-2.7 to Python site-packages.My site-packages location is  C:\Python27\Lib\site-packages.
After the steps above, import pygraphviz should succeed on Python interpreter..

The link which i presented in the beginning of this post worked for me.. However, some slightly different solutions exist (unfortunately, they did not help much my condition):