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

Wednesday, September 16, 2015

LINQ: Problem with Deferred execution

This morning I started my day googling for an exception in the code:
Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries
And as most cases, I ended up with a Stackover solution:


The code that I was cleaning up was as bellow:


This was breaking for large data but working fine for small data.

It was breaking when the Except() is used to compare large data – the reason is EF most cases does Deferred execution- so all the incompleteCourseId, completedCourseId and requeriedCourseId are evaluated when the Except() is called. For small data it can execute – but for large data it breaks.

Similar thing can happen when complex query needs to be executed through LINQ; So possibly its a good idea to split the queries into multiple ones and evaluate whenever required/whenever requires fetching large data.

So the solution is I forcefully evaluated each of the query using ToList() and it seems it is working good now. Off course cost is multiple SQL call.

Reference:
http://stackoverflow.com/questions/14163390/some-part-of-your-sql-statement-is-nested-too-deeply-rewrite-the-query-or-break


Monday, June 15, 2015

Passing EventArguments to RelayCommand in MVVM

I was to override the default behavior of the editable ComboBox control. Where if clicked the in the combobox the text will always be selected.

The View :
<ComboBox x:Name="cboList" FontSize="25"
     TabIndex="8" MaxDropDownHeight="270"
     Style="{DynamicResource ComboBoxStyleLargeScroll}"
     DisplayMemberPath="Name" SelectedValuePath="RepID"
     ItemsSource="{Binding VisitorHostList, UpdateSourceTrigger=PropertyChanged
   ,ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"
     SelectedItem="{Binding UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True, ValidatesOnDataErrors=True
   ,NotifyOnValidationError=True, Path=SelectedVisitorHost}"
     SelectedValue="{Binding Inductee.HostRepID, UpdateSourceTrigger=PropertyChanged
   ,ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" IsEditable="True" VerticalContentAlignment="Bottom" MinWidth="0" MaxWidth="351">
                                    <ComboBox.Resources>
                                        <Style TargetType="{x:Type ScrollBar}">
                                            <Setter Property="Width" Value="50" />
                                        </Style>
                                    </ComboBox.Resources>
                                    <i:Interaction.Triggers>
                                        <i:EventTrigger EventName="GotFocus">
                                            <cmd:EventToCommand Command="{Binding GotFocusCommand, Mode=OneWay}" MustToggleIsEnabledValue="True"/>
                                        </i:EventTrigger>
                                        <i:EventTrigger EventName="PreviewMouseUp">
                                            <cmd:EventToCommand Command="{Binding PreviewMouseUpCommand, Mode=OneWay}" MustToggleIsEnabledValue="True" PassEventArgsToCommand="True" />
                                        </i:EventTrigger>

                                    </i:Interaction.Triggers>
                                </ComboBox>
The ViewModel :
#region Commands
  public ICommand PreviewMouseUpCommand { get; set; }
 #endregion
#region Constructor
        public MyViewModel()
        {
         
            PreviewMouseUpCommand = new RelayCommand<MouseButtonEventArgs>(PreviewMouseUp);
         
        }
#endregion
#region eventhandler
private void PreviewMouseUp(MouseButtonEventArgs e)
        {
            try
            {
                System.Windows.Controls.ComboBox cboHostList = e.Source as System.Windows.Controls.ComboBox;
                if (cboHostList != null)
                {
                    var cboEditableTextBox = (cboHostList.Template.FindName("PART_EditableTextBox", cboHostList) as System.Windows.Controls.TextBox);
                    if (cboEditableTextBox != null && !cboHostList.IsDropDownOpen)
                    {
                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            cboEditableTextBox.SelectAll();
                            cboEditableTextBox.Focus();
                        }));
                    }
                }
            }
            catch(Exception ex)
            {
                Util.Logger(typeof(MyViewModel)).Error("Error in PreviewMouseUp of ComboboxList", ex);
            }
        }
#endregion

Friday, May 22, 2015

Open source Push Server

  • PushSharp: [C#] :A server-side library for sending Push Notifications to iOS (iPhone/iPad APNS), OSX (APNS 10.8+) Android (C2DM and GCM - Google Cloud Message), Chrome (GCM) Windows Phone, Windows 8, Blackberry (PAP), and Amazon (ADM) devices!
  • PushSharp.Web: [C#] A web wrapper for PushSharp
  • AeoroGear UnifiedPushSeerver: [JAVA]: Easy and promising - does have a Openshift gear and can be tested over Openshift
  • Pushd:[Node.js] :Pushd is a pluggable "unified" push server for server-side notification to mobile native apps, web apps etc. With pushd you can send push notifications to any supported mobile platform, web app or HTTP server from a single entry point. Pushd takes care of which device is subscribed to which event and is designed to support an unlimited amount of subscribable events.
  • Loopback.io: [Node.js]: Loopback is basically a nodejs framework to easily create api - but it does have component to create push servers.
  • Node-Push-Server: [Node.js]: It looks like a stripped down version of Pushd.

Monday, October 28, 2013

"WHERE IN" for LINQ

I was trying to convert the following query to LINQ :

select Osid,OsName,CompanyId,Pid,description,type from OrganisationStructure where OSId in (" + location + ") and type='location'
Where location is a string like '123,2345,12356' ...
What I got on some places the where in clause is converted as bellow :

List<string> locList = location.Split(',').ToList();
var orgloc = (from b in context.OrganisationStructures
                                  where locList.Contains(b.OSId.ToString()) select new{b.OSId,b.OSName,b.CompanyId,b.pID,b.description,b.Type});
This was not giving any error on design time. But while debugging I got the following error:
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression
The reason is LINQ to SQL doesn't know how to translate the .ToString() call to a SQL expression.Therefore I had to change it like bellow:
var orgloc = (from b in context.OrganisationStructures select new{b.OSId,b.OSName,b.CompanyId,b.pID,b.description,b.Type}).ToList().Where( s => locList.Contains(s.OSId.ToString()) && s.Type.Equals("location") ) ;

Refrence :

Tuesday, December 7, 2010

Multi-Threaded Socket programming using C# : first step for a chat application

Just arranged some code to create a server and a client application that can talk over separate threads. The code  is not that efficient, yet, the programs can be used as the very basic for writing your own chat servers and clients (I din try though :P)

Download and play with the code by yourself and feel free to comment.
[The code is in VB.Net; I'm no more a VB coder though :S I had to prepare it for one of my cousins.]

Wednesday, September 9, 2009

C# Word Counter

I don write code for long time. I wrote this program just to count an essay ;) So not a very big deal actually.
What I have practiced here :
  • Openfiledialog : How to open and select a file.
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "File to read";
fDialog.Filter = "txt files|*.txt";
fDialog.InitialDirectory = @"C:\Documents and Settings\roni\Desktop\Temp";

if (fDialog.ShowDialog() == DialogResult.OK)
//MessageBox.Show(fDialog.FileName.ToString());
  • Reading a file:
StringBuilder newFile = new StringBuilder();
string filestring = File.ReadAllText(@"C:\p_keydump.txt");
filestring = filestring.Replace("\r\n", ",");
  • Count the number of words is the file.
countedWords = strText.Split(' ').Length;