I have a context like this:
/// <summary>
/// Constructeur qui récupère automatiquement la chaîne de connection.
/// </summary>
/// <remarks>Nécessaire pour les commandes de migrations de EF > 4.3.</remarks>
public ScsContext()
: base(ConfigurationUtility.GetConnectionString())
{
}
/// <summary>
/// Constructeur qui prend en paramètre une chaine de connection.
/// </summary>
/// <param name="connectionString">Chaîne de connexion.</param>
public ScsContext(string connectionString)
: base(connectionString)
{
}
I selected my persistence assembly which contains the ScsContext. I've been able to select the ScsContext and I chose the parameterless constructor and then the config file where the connection string is located.
I did a test to see if it could connect.. yes it could.
I can see all the tables in LindPaq but it failed to do any queries.. like Accounts.Take (100) I get the error saying the name 'Accounts' does not exist in the current context.
Any ideas ? I am pretty sure I have the right DLL and everything.
Here is what I did when I had this problem
using (var cntx = new DataContext("Server=LAPTOP\\EXPRESS2012;Database=Database;Trusted_Connection=True;"))
{
var users = cntx.Set<User>().ToList();
users.Dump();
}
I also had to add a reference in LinqPad to the assembly that contained my models\entities then added a namespace import. Just press F4 in linqpad and you can see how to add the references and namespace imports. Also, change the language to C# statement.
Related
I update my app's metrics a lot in registry, and want to know which method of writing to system registry is significantly faster.
If you use a .NET decompiler to peek into the source code of the Interaction class/module under the Microsoft.VisualBasic namespace, you'll find that the SaveSetting() method actually uses SetValue() under the hood:*
/// <summary>Saves or creates an application entry in the Windows registry. The My feature gives you greater productivity and performance in registry operations than SaveSetting. For more information, see <see cref="P:Microsoft.VisualBasic.Devices.ServerComputer.Registry" />.</summary>
/// <param name="AppName">Required. String expression containing the name of the application or project to which the setting applies.</param>
/// <param name="Section">Required. String expression containing the name of the section in which the key setting is being saved.</param>
/// <param name="Key">Required. String expression containing the name of the key setting being saved.</param>
/// <param name="Setting">Required. Expression containing the value to which <paramref name="Key" /> is being set.</param>
/// <exception cref="T:System.ArgumentException">Key registry could not be created, or user is not logged in.</exception>
/// <filterpriority>1</filterpriority>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.RegistryPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
public static void SaveSetting(string AppName, string Section, string Key, string Setting)
{
Interaction.CheckPathComponent(AppName);
Interaction.CheckPathComponent(Section);
Interaction.CheckPathComponent(Key);
string text = Interaction.FormRegKey(AppName, Section);
RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(text);
if (registryKey == null)
{
throw new ArgumentException(Utils.GetResourceString("Interaction_ResKeyNotCreated1", new string[]
{
text
}));
}
try
{
registryKey.SetValue(Key, Setting);
}
catch (Exception ex)
{
throw ex;
}
finally
{
registryKey.Close();
}
}
Or in VB, if you prefer:
''' <summary>Saves or creates an application entry in the Windows registry. The My feature gives you greater productivity and performance in registry operations than SaveSetting. For more information, see <see cref="P:Microsoft.VisualBasic.Devices.ServerComputer.Registry" />.</summary>
''' <param name="AppName">Required. String expression containing the name of the application or project to which the setting applies.</param>
''' <param name="Section">Required. String expression containing the name of the section in which the key setting is being saved.</param>
''' <param name="Key">Required. String expression containing the name of the key setting being saved.</param>
''' <param name="Setting">Required. Expression containing the value to which <paramref name="Key" /> is being set.</param>
''' <exception cref="T:System.ArgumentException">Key registry could not be created, or user is not logged in.</exception>
''' <filterpriority>1</filterpriority>
''' <PermissionSet>
''' <IPermission class="System.Security.Permissions.RegistryPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
''' </PermissionSet>
Public Sub SaveSetting(AppName As String, Section As String, Key As String, Setting As String)
Interaction.CheckPathComponent(AppName)
Interaction.CheckPathComponent(Section)
Interaction.CheckPathComponent(Key)
Dim text As String = Interaction.FormRegKey(AppName, Section)
Dim registryKey As RegistryKey = Registry.CurrentUser.CreateSubKey(text)
If registryKey Is Nothing Then
Throw New ArgumentException(Utils.GetResourceString("Interaction_ResKeyNotCreated1", New String() { text }))
End If
Try
registryKey.SetValue(Key, Setting)
Catch ex As Exception
Throw ex
Finally
registryKey.Close()
End Try
End Sub
Therefore, I would expect them to have the same performance in this particular case (assuming you will be basically replicating the same behavior). However, the Microsoft.Win32.Registry class (or the My.Computer.Registry property, which is just a wrapper for the said class) is going to be more flexible and provides more options as noted in the documentation (thanks, Jimi!) and in the XML comments shown above.
As to the performance, to be 100% certain (assuming you actually need to), then you should always measure.
* This code was extracted using ILSpy.
I want to share a file that exists in Google Drive with a specified user. The file is not public.
Firstly, I want to show a file in a WebBrowser control.
Secondly, I want that when I share an URL to a different user, they can then show the file in their Google Drive.
Here is my code, I already can do the first step but for the second step, I don't know how I can do it.
Public Sub A(fichier As String)
CreateService()
Dim url As String = ""
Dim list = Service.Files.List()
Dim count = list.Execute()
For Each fich In count.Items
If (fich.Title) = fichier Then
url = fich.WebContentLink
Exit For
End If
Next
affich_image.img.Navigate(url)
affich_image.Show()
You can use the permissions.insert method.
Inserts a permission for a file or Team Drive.
To see the parameters and further details, try to visit the documentation.
Here, I provide you the sample code for .NET that was introduced in the said documentation.
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using System.Net;
// ...
public class MyClass {
// ...
/// <summary>
/// Insert a new permission.
/// </summary>
/// <param name="service">Drive API service instance.</param>
/// <param name="fileId">ID of the file to insert permission for.</param>
/// <param name="value">
/// User or group e-mail address, domain name or null for "default" type.
/// </param>
/// <param name="type">The value "user", "group", "domain" or "default".</param>
/// <param name="role">The value "owner", "writer" or "reader".</param>
/// <returns>The inserted permission, null is returned if an API error occurred</returns>
public static Permission InsertPermission(DriveService service, String fileId, String value,
String type, String role) {
Permission newPermission = new Permission();
newPermission.Value = value;
newPermission.Type = type;
newPermission.Role = role;
try {
return service.Permissions.Insert(newPermission, fileId).Execute();
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
}
return null;
}
// ...
}
You may also visit this SO post for further discussion.
I was trying to test message sent from tested actor, but getting timeout exception and a Dead letter info.
As I am using ninject - created a mock method which always replays with probe actor reference.
Am I missing something here?
Assert.Fail failed. Failed: Timeout 00:00:03 while waiting for a message of type System.Type
at Akka.TestKit.TestKitBase.InternalExpectMsgEnvelope(Nullable`1 timeout, Action`2 assert, String hint, Boolean shouldLog)
at Akka.TestKit.TestKitBase.InternalExpectMsgEnvelope(Nullable`1 timeout, Action`1 msgAssert, Action`1 senderAssert, String hint)
at Akka.TestKit.TestKitBase.InternalExpectMsg(Nullable`1 timeout, Action`1 msgAssert, String hint)
at Akka.TestKit.TestKitBase.ExpectMsg(T message, Nullable`1 timeout, String hint)
at
AutoApply.UnitTests.SomethingProcessorActors.SomethingProcessorActorTests.SomethingProcessorActorWhenMergeDataAndGetsNoProfilesLogsThat()
in SomethingProcessorActorTests.cs: line 58
[WARNING][12/02/2016 16:12:43][Thread 0009][akka://test/user/testProbe] DeadLetter from [akka://test/temp/d]
to [akka://test/user/testProbe]:
[INFO][12/02/2016 16:12:43][Thread 0011][akka://test/user/testProbe] Message
GetOneSomethingAndRemoveFromList from akka://test/temp/d to
akka://test/user/testProbe was not delivered. 1 dead letters
encountered.
Debug Trace:
Setting probe reference: akka://test/user/testProbe
GetDataActorPath for:SomethingsDataActor
GetDataActorPath =>akka://test/user/testProbe
GetDataActorPath for:SomethingCollectorActor
GetDataActorPath =>akka://test/user/testProbe
[TestClass]
public class SomethingProcessorActorTests : TestKit
{
/// <summary>The factory helper</summary>
private IMockingExtension factoryHelper;
private TestProbe probeActorRef;
/// <summary>Configurations this instance.</summary>
[TestInitialize]
public void Config()
{
this.probeActorRef = this.CreateTestProbe("testProbe");
this.factoryHelper = new MockingFactoryHelper();
this.factoryHelper.SetProbe(this.probeActorRef.TestActor);
}
/// <summary>Somethings the processor actor when merge data and gets no profiles logs that.</summary>
[TestMethod]
public void SomethingProcessorActorWhenMergeDataAndGetsNoProfilesLogsThat()
{
// arrange
var actor =
this.Sys.ActorOf(
Props.Create(() => new SomethingProcessorActor(this.factoryHelper as IActorPathAndFactory)),
"SomethingActor");
// act
actor.Tell(new SomethingProcessorActor.ProcessSomethings());
// assert
this.probeActorRef.ExpectMsgFrom<SomethingsDataActor.GetOneSomethingAndRemoveFromList>(actor, new TimeSpan(0, 0, 0, 5));
}
}
=======================
public partial class SomethingProcessorActor : ReceiveActor
{
/// <summary>The helper</summary>
private readonly IActorPathAndFactory helper;
/// <summary>The log</summary>
private readonly ILoggingAdapter log = Context.GetLogger();
/// <summary>The vote execution profile</summary>
private List<SomethingProcessingObject> voteExecutionProfile = new List<SomethingProcessingObject>();
/// <summary>
/// Initializes a new instance of the <see cref="SomethingProcessorActor"/> class.
/// </summary>
/// <param name="helper">
/// The helper.
/// </param>
public SomethingProcessorActor(IActorPathAndFactory helper)
{
this.helper = helper;
this.Receive<ProcessSomethings>(
x =>
{
this.log.Debug("Received: ProcessSomethings");
this.BecomeStacked(this.Working);
this.RetriveSomethingAndPushForProcessing();
});
}
/// <summary>Supervisors strategy.</summary>
/// <returns>Supervisors strategy for that actor</returns>
protected override SupervisorStrategy SupervisorStrategy()
{
return new AllForOneStrategy(10, 3000, Decider.From(x => Directive.Stop));
}
/// <summary>
/// The merge data.
/// </summary>
private void RetriveSomethingAndPushForProcessing()
{
this.log.Debug($"Processing Somethings...");
var SomethingActor1 = this.helper.GetActorPath(ActorsEnum.SomethingsDataActor);
var SomethingActor2 = this.helper.GetActorPath(ActorsEnum.SomethingCollectorActor);
var something = (SomethingDto)SomethingActor1.Ask(new SomethingsDataActor.GetOneSomethingAndRemoveFromList()).Result;
while (Something.SomethingId>0)
{
this.log.Debug($"Sending data to SomethingCollector with Something id: {Something.SomethingId}");
SomethingActor2.Tell(new SomethingCollectorActor.ProcessSomethingDto(Something));
Something = (SomethingDto)SomethingActor1.Ask(new SomethingsDataActor.GetOneSomethingAndRemoveFromList()).Result;
}
this.log.Debug("Sending data to SomethingCollector -- ALL SENT");
this.UnbecomeStacked();
}
The mock objects just send probe actor as per every request
public ActorSelection GetActorPath(ActorsEnum actorsEnum)
{
Debug.WriteLine("GetDataActorPath for:" + actorsEnum);
Debug.WriteLine("GetDataActorPath =>" + this.probeRef.Path);
return this.Sys.ActorSelection(this.probeRef.Path);
}
public void SetProbe(IActorRef actorRef)
{
Debug.WriteLine("Setting probe reference: " + actorRef.Path);
this.probeRef = actorRef;
}
ignition overview
Ok so a few things.
First of all: You are expecting on a message of the type: SomethingsDataActor.GetOneSomethingAndRemoveFromList.
But it doesn't look like you are actually passing this message to an actorref that is represented by the testprobe. But its hard to be sure since you only pasted halve the code.
Second:
Using ask inside an actor is considered an anti pattern, and can easily be avoided by employing a more conversationalist style of communication.
Using actor.ask().Result is even worse because it can lead to deadlocks if your not carefull. (what happens when the database actor crashes because your network is down? potentially no response will ever be send back and the default Ask timeout is infinite)
Ask should only really be used to communicate with an actor from outside the actor system.
The problem was with mocking class that was inhering TestClass,
decided for that to have "Actor System Reference"
return this.Sys.ActorSelection(this.probeRef.Ref.Path);
but should be:
return this.probeRef.ActorSelection(this.probeRef.Ref.Path);
This inheritance was creating a second independednt actor system.....
Thanks #Dantar for help!
I've changed my DefaultIndexConfiguration config file to search based on synonyms (http://firebreaksice.com/sitecore-synonym-search-with-lucene/) and it works fine. However this is based in a xml file in the filesystem
<param hint="engine" type="Sitecore.ContentSearch.LuceneProvider.Analyzers.XmlSynonymEngine, Sitecore.ContentSearch.LuceneProvider">
<param hint="xmlSynonymFilePath">C:\inetpub\wwwroot\website\Data\synonyms.xml</param>
</param>
What I'd like to do is to have this data manageable in the CMS.
Does anyone know how can I set this xmlSynonymFilePath parameter to achieve what I want? Or am I missing something?
The simplest solution would be to create an item in Sitecore (e.g. /sitecore/system/synonyms) using the template with only one multi-line field called Synonyms and keep xml in this field instead of reading it from file.
Then create your custom implementation of ISynonymEngine like that (this is just simplest example - it's NOT production ready code):
public class CustomSynonymEngine : Sitecore.ContentSearch.LuceneProvider.Analyzers.ISynonymEngine
{
private readonly List<ReadOnlyCollection<string>> _synonymGroups = new List<ReadOnlyCollection<string>>();
public CustomSynonymEngine()
{
Database database = Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database ?? Database.GetDatabase("web");
Item item = database.GetItem("/sitecore/system/synonyms"); // or whatever is the path
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(item["synonyms"]);
XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/synonyms/group");
if (xmlNodeList == null)
throw new InvalidOperationException("There are no synonym groups in the file.");
foreach (IEnumerable source in xmlNodeList)
_synonymGroups.Add(
new ReadOnlyCollection<string>(
source.Cast<XmlNode>().Select(synNode => synNode.InnerText.Trim().ToLower()).ToList()));
}
public IEnumerable<string> GetSynonyms(string word)
{
Assert.ArgumentNotNull(word, "word");
foreach (ReadOnlyCollection<string> readOnlyCollection in _synonymGroups)
{
if (readOnlyCollection.Contains(word))
return readOnlyCollection;
}
return null;
}
}
And register your engine in Sitecore configuration instead of default engine:
<analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.PerExecutionContextAnalyzer, Sitecore.ContentSearch.LuceneProvider">
<param desc="defaultAnalyzer" type="Sitecore.ContentSearch.LuceneProvider.Analyzers.DefaultPerFieldAnalyzer, Sitecore.ContentSearch.LuceneProvider">
<param desc="defaultAnalyzer" type="Sitecore.ContentSearch.LuceneProvider.Analyzers.SynonymAnalyzer, Sitecore.ContentSearch.LuceneProvider">
<param hint="engine" type="My.Assembly.Namespace.CustomSynonymEngine, My.Assembly">
</param>
</param>
</param>
</analyzer>
This is NOT production ready code - it only reads the list of synonyms once when the CustomSynonymsEngine class is instantiated (I don't know if Sitecore keeps the instance or creates new instance multiple times).
You should extend this code to cache the synonyms and clear the cache every time a synonyms list is changed.
Also you should think about having a nice synonyms structure in the Sitecore tree instead of having a one item and xml blob which will be really hard to maintain.
I know there's a lot of information about this subject, but I just can't seem to find an answer suitable to my specific needs:
I opened a new MVC 4.0 basic application (meaning, no "AuthConfig.cs" file exist).
I have already successfully implemented Facebook sign-in.
I can't seem to find any way to do the same with Google.
I already have a custom "Connect with google" button. I need a very simple code to authenticate using google. Please bare in mind, that after authentication, I need to get user information, and also get a hold of the user's calendar.
Please help
Thank you.
Some Code to help you get started
In AuthConfig file
OAuthWebSecurity.RegisterClient(new Mvc.GoogleCustomClient(), "Google", null);
In GoogleCustomClient.cs
public class GoogleCustomClient : OpenIdClient
{
public GoogleCustomClient()
: base("google", WellKnownProviders.Google) { }
/// <summary>
/// Gets the extra data obtained from the response message when authentication is successful.
/// </summary>
/// <param name="response">
/// The response message.
/// </param>
/// <returns>A dictionary of profile data; or null if no data is available.</returns>
protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response)
{
FetchResponse fetchResponse = response.GetExtension<FetchResponse>();
if (fetchResponse != null)
{
var extraData = new Dictionary<string, string>();
extraData.Add("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email));
extraData.Add("country", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country));
extraData.Add("firstName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First));
extraData.Add("lastName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last));
return extraData;
}
return null;
}
/// <summary>
/// Called just before the authentication request is sent to service provider.
/// </summary>
/// <param name="request">
/// The request.
/// </param>
protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request)
{
// Attribute Exchange extensions
var fetchRequest = new FetchRequest();
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
request.AddExtension(fetchRequest);
}
}
You can Use this Code to retrieve the User Information from google.