Use dictionary inside linq query - linq

I want to use some dictionary inside my linq query, however since LINQ to entities can't translate the use of the dictionary it throws an exception.
Actually the same problem was described in the following question:
linq to entity framework: use dictionary in query
I wasn't satisfied of the solution which was described there. I'm sure there is some other solution for this problem. I don't want to use the ToList/ToArray method - which will bring all data to memory.
What is the best way to solve this issue, without pulling the db data to memory?

Your example looks like you actually don't need the functionality of a dictionary, you simply want to have WHERE IN functionality.
You could use the following to achieve this:
var countries = Countries.WhereIn(x => x.CountryId, dict.Keys);
WhereIn is not a built in query operator, you need to write it yourself - or copy:
/// <summary>
/// Holds extension methods that simplify querying.
/// </summary>
public static class QueryExtensions
{
/// <summary>
/// Return the element that the specified property's value is contained in the specified values.
/// </summary>
/// <typeparam name="TElement"> The type of the element. </typeparam>
/// <typeparam name="TValue"> The type of the values. </typeparam>
/// <param name="source"> The source. </param>
/// <param name="propertySelector"> The property to be tested. </param>
/// <param name="values"> The accepted values of the property. </param>
/// <returns> The accepted elements. </returns>
public static IQueryable<TElement> WhereIn<TElement, TValue>(
this IQueryable<TElement> source,
Expression<Func<TElement, TValue>> propertySelector,
params TValue[] values)
{
return source.Where(GetWhereInExpression(propertySelector, values));
}
/// <summary>
/// Return the element that the specified property's value is contained in the specified values.
/// </summary>
/// <typeparam name="TElement"> The type of the element. </typeparam>
/// <typeparam name="TValue"> The type of the values. </typeparam>
/// <param name="source"> The source. </param>
/// <param name="propertySelector"> The property to be tested. </param>
/// <param name="values"> The accepted values of the property. </param>
/// <returns> The accepted elements. </returns>
public static IQueryable<TElement> WhereIn<TElement, TValue>(
this IQueryable<TElement> source,
Expression<Func<TElement, TValue>> propertySelector,
IEnumerable<TValue> values)
{
return source.Where(GetWhereInExpression(propertySelector, values.ToList()));
}
/// <summary>
/// Gets the expression for a "where in" condition.
/// </summary>
/// <typeparam name="TElement"> The type of the element. </typeparam>
/// <typeparam name="TValue"> The type of the value. </typeparam>
/// <param name="propertySelector"> The property selector. </param>
/// <param name="values"> The values. </param>
/// <returns> The expression. </returns>
private static Expression<Func<TElement, bool>> GetWhereInExpression<TElement, TValue>(
Expression<Func<TElement, TValue>> propertySelector, ICollection<TValue> values)
{
var p = propertySelector.Parameters.Single();
if (!values.Any())
return e => false;
var equals =
values.Select(
value =>
(Expression)Expression.Equal(propertySelector.Body, Expression.Constant(value, typeof(TValue))));
var body = equals.Aggregate(Expression.OrElse);
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
}

Related

Signin Cards for bot in Teams

Can anyone tell Where can I get a JSON for Microsoft Sigin card for Teams bot and how to view it in a visualizer and can it be used to mask the password.
This is the OauthCard.cs file:
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bot.Schema
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A card representing a request to perform a sign in via OAuth
/// </summary>
public partial class OAuthCard
{
/// <summary>
/// Initializes a new instance of the OAuthCard class.
/// </summary>
public OAuthCard()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the OAuthCard class.
/// </summary>
/// <param name="text">Text for signin request</param>
/// <param name="connectionName">The name of the registered
/// connection</param>
/// <param name="buttons">Action to use to perform signin</param>
public OAuthCard(string text = default(string), string connectionName = default(string), IList<CardAction> buttons = default(IList<CardAction>))
{
Text = text;
ConnectionName = connectionName;
Buttons = buttons;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets text for signin request
/// </summary>
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
/// <summary>
/// Gets or sets the name of the registered connection
/// </summary>
[JsonProperty(PropertyName = "connectionName")]
public string ConnectionName { get; set; }
/// <summary>
/// Gets or sets action to use to perform signin
/// </summary>
[JsonProperty(PropertyName = "buttons")]
public IList<CardAction> Buttons { get; set; }
}
}
It can be found here. That being said, AFAIK, there is no visualizer for it, it's not in JSON, and there's nothing there to mask.
You can create a Sign In card in c#
SigninCard signincard = new SigninCard()
{
Text = "Click here to sign in",
Buttons = new List<CardAction>() {
new CardAction()
{
Title = "Authentication Required",
Type = ActionTypes.OpenUrl,
Value = $"{authenticationUrl}?{encodedCookie}"
}
}
};
Please give a try.

Xamarin Shared Project - MP3 Streaming

I am writing a simple streaming mp3 player in a Xamarin shared project. I have this solution which works perfectly with iOS. I can also use the media player solution for Android (i guess) to achieve the same. Any recommendation on doing this the right way so that maximum code is shared? As i understand, i have the below options
Write an abstract class with the basic audio features like streaming, buffering etc in shared and then implement them in platform specific
Create user controls in each platform specific solution
Write a Portable Class Library
I have gone through this, but not sure which is the most sensible way to proceed given my requirement and what i have in hand.
I use this as th interface for the mediaplayer:
public delegate void StatusChangedEventHandler(object sender, EventArgs e);
public delegate void CoverReloadedEventHandler(object sender, EventArgs e);
public delegate void PlayingEventHandler(object sender, EventArgs e);
public delegate void BufferingEventHandler(object sender, EventArgs e);
/// <summary>
/// The main purpose of this class is to be a controlling unit for all the single MediaItem implementations, who
/// in themselve can play their media, but need a central controling unit, surrounding them
/// </summary>
public interface IMediaPlayer
{
/// <summary>
/// Reading the current status of the player (STOPPED, PAUSED, PLAYING, LOADING - initialization and buffering is combined here)
/// </summary>
PlayerStatus Status { get; }
/// <summary>
/// Raised when the status changes (playing, pause, buffering)
/// </summary>
event StatusChangedEventHandler StatusChanged;
/// <summary>
/// Raised when the cover on the player changes
/// </summary>
event CoverReloadedEventHandler CoverReloaded;
/// <summary>
/// Raised at least every second when the player is playing.
/// </summary>
event PlayingEventHandler Playing;
/// <summary>
/// Raised each time the buffering is updated by the player.
/// </summary>
event BufferingEventHandler Buffering;
/// <summary>
/// Starts playing from the current position
/// </summary>
Task Play();
/// <summary>
/// Stops playing
/// </summary>
Task Stop();
/// <summary>
/// Stops playing but retains position
/// </summary>
Task Pause();
/// <summary>
/// Gets the players position in milliseconds
/// </summary>
int Position { get; }
/// <summary>
/// Gets the source duration in milliseconds
/// If the response is -1, the duration is unknown or the player is still buffering.
/// </summary>
int Duration { get; }
/// <summary>
/// Gets the buffered time in milliseconds
/// </summary>
int Buffered { get; }
/// <summary>
/// Gets the current cover. The class for the instance depends on the platform.
/// Returns NULL if unknown.
/// </summary>
object Cover { get; }
/// <summary>
/// Changes position to the specified number of milliseconds from zero
/// </summary>
Task Seek(int position);
/// <summary>
/// Should be the same as calling PlayByPosition(Queue.size()+1)
/// Maybe you'll want to preload the next song into memory ...
/// </summary>
Task PlayNext();
/// <summary>
/// Start playing if nothing is playing, otherwise it pauses the current media
/// </summary>
Task PlayPause();
/// <summary>
/// Should be the same as calling PlayByPosition(Queue.size()-1).
/// Maybe you'll want to keep the last song in memory ...
/// </summary>
Task PlayPrevious();
/// <summary>
/// Start playing a track by its position in the Queue
/// </summary>
Task PlayByPosition(int index);
}
Also i have a custom queue which could be helpful to you:
public interface IQueue : ICollection<Track>, INotifyCollectionChanged, INotifyPropertyChanged
{
/// <summary>
/// Activates or deactivates the Repeat option
/// </summary>
bool Repeat { get; set; }
/// <summary>
/// Activates or deactivates the Shuffle option
/// </summary>
bool Shuffle { get; set; }
/// <summary>
/// If the Queue has a next track
/// </summary>
bool HasNext();
/// <summary>
/// If the Queue has a previous track
/// </summary>
bool HasPrevious();
/// <summary>
/// Get the current track from the Queue
/// </summary>
Track Current { get; }
/// <summary>
/// Get the current playing index the Queue
/// </summary>
int Index { get; }
void setPreviousAsCurrent();
void setNextAsCurrent();
void setIndexAsCurrent(int index);
void AddRange(IEnumerable<Track> items);
}
The playerstatus for me are:
public enum PlayerStatus
{
STOPPED,
PAUSED,
PLAYING,
LOADING
}

Automatic comment via "///" in Visual Studio 2010 above a Delegate

my delegate: I typed over the delegate in VS2010 the 3 slashes "///" and the typical automatic comment appears.
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="?"></typeparam>
/// <param name="param"></param>
/// <returns></returns>
private delegate IEnumerable<T> SearchInputText<T, string>(string param)
Why does it make the 2nd name = "?" ??? should it not be STRING ?
Because this code is not compiled:
error CS0081: Type parameter declaration must be an identifier not a type

ActiveDirectory query performance for not including

I'm curious as to whether the following will negatively impact performance in a significant way...
I have a web form with an input box and grid (could be any form of application really) and allows the user to search Active Directory for users...I don't want user accounts that have the $ as part of there sAMAccountName and so am wondering whether I should have them returned and then filter them out in a loop in the application or whether they should be excluded in the ActiveDirectory filter like the following:
(&(objectCateogry=person)(objectClass=user)(!(sAMAccountName=*$*))(cn=<Insert User Query>))
I guess it's the *$* that i'm concerned will impact performance...any insight would be greatly appreciated!
I would include (!(sAMAccountName=*$*)) in the query for the following reasons:
It is indexed in Active Directory so searches are quick.
In most environments domain controllers aren't hit as hard as web servers and have CPU and RAM to spare.
I'm just guessing but I would think that the extra entries that the domain controllers will have to process and send to the web server would actually make everything take a little longer. You could try it both ways in your environment and measure the difference.
Also, you could take a look at the classes in System.DirectoryServices.Protocols if you're concerned with performance.
The filter about AD as follwing:
class ExpressionTemplates
{
/// <summary>
/// The start with expression. eg: "({0}={1}*)".
/// </summary>
public readonly static string StartWithExpression = "({0}={1}*)";
/// <summary>
/// The end with expression. eg: "({0}=*{1})".
/// </summary>
public readonly static string EndWithExpression = "({0}=*{1})";
/// <summary>
/// The has a value expression. eg: "({0}=*)".
/// </summary>
public readonly static string HasAValueExpression = "({0}=*)";
/// <summary>
/// The has no value expression. eg: "(!{0}=*)".
/// </summary>
public readonly static string HasNoValueExpression = "(!{0}=*)";
/// <summary>
/// The is expression. eg: "({0}={1})".
/// </summary>
public readonly static string IsExpression = "({0}={1})";
/// <summary>
/// The is not expression. eg: "(!{0}={1})".
/// </summary>
public readonly static string IsNotExpression = "(!{0}={1})";
/// <summary>
/// The and expression. eg: "(&{0})".
/// </summary>
public readonly static string And = "(&{0})";
/// <summary>
/// The or expression. eg: "(|{0})".
/// </summary>
public readonly static string Or = "(|{0})";
/// <summary>
/// The parenthesis expression. eg: "({0})".
/// </summary>
public readonly static string Parenthesis = "({0})";
/// <summary>
/// The join expression. eg: "{0}{1}".
/// </summary>
public readonly static string Join = "{0}{1}";
}
You can refer my OSS project which base on ActiveRecord pattern as following(Because it is open source you can find out how to operate the AD with DirectoryEntry, DirectoryEntry is not only support the LDAP protocol but also IIS, WIN and so on, so I develop this lib):
class ComplexFilterUnitTest : BaseUnitTest
{
[TestCase]
public void TestComplexFilter()
{
IFilter filter =
new And(
new IsUser(),
new Is(OrganizationalUnitAttributeNames.OU, "pangxiaoliangOU"),
new Or(
new StartWith(AttributeNames.CN, "pang"),
new And(
new EndWith(AttributeNames.CN, "liu"),
new Is(PersonAttributeNames.Mail, "mv#live.cn")
)
)
);
Assert.AreEqual("(&(objectClass=user)(ou=pangxiaoliangOU)(|(cn=pang*)(&(cn=*liu)(mail=mv#live.cn))))", filter.BuildFilter());
foreach (var userObject in UserObject.FindAll(this.ADOperator, filter))
{
using (userObject)
{
Console.WriteLine(userObject.DisplayName);
}
}
}
}
https://landpyactivedirectory.codeplex.com/documentation
And you will find it easy to operate the AD with it, if you have no interest with it please ignore my answer.
Any question about AD please contact me :)

Automatically adding .Net code comments

Where can I find a Visual Studio plug-in that automatically generates documentation header for methods and properties?
Example the comment to a property could look like this:
/// <summary>
/// Gets or sets the value of message
/// </summary>
public static string Message
{
get
{
return message;
}
set
{
message = value;
}
}
Ghostdoc from http://www.roland-weigelt.de/ghostdoc/
GhostDoc is the usual suspect.
As another poster mentioned, Visual Studio also does this to an extent by entering 3 '///' (forward slashes) on the line preceding a property/method/class definition.
Visual Studio does this automatically. Just position the cursor directly above the method and enter three '/'s
for example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcWidgets.Models
{
/// <summary>
/// This is a summary comment
/// </summary>
public class Comment
{
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="birthdate"></param>
/// <param name="website"></param>
/// <returns></returns>
public int SomeMethod(string name, DateTime birthdate, Uri website)
{
return 0;
}
}
}
You can then generate an XML comment file and then generate a Help file using SandCastle.
You may have to enable this feature in the Text Editor/C#/Advanced options dialog.

Resources