Strings.PlatformNotSupported_DataSqlClient - entity-framework

I have an exeption
System.PlatformNotSupportedException: 'Microsoft.Data.SqlClient is not supported on this platform.'
using (var connection = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(queryString, connection))
{
cmd.Connection = connection;
connection.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
return true;
}
}
}
}
My CSProj file who contain all references of project
Exeption

the problem is solved
I added the dll Microsoft.Data.SqlClient with same version to the exe program which calls my c# library which contains Microsoft.Data.SqlClient same version 4.1.0

Related

protobuf-net causing Invalid wire type error during deserialization

Working on a POC of transitioning from BinaryFormater to Protobuf for Serialization and deserialization inorder to reduce the deserialization time. While trying to deserialize using the protobuf library I get the following error "Invalid wire-type; this usually means you have over-written a file without truncating or setting the length" while deserializing a file in a rest web API project but the same code runs fine in another web job project with same .Net version.
protobuf-net Version: 3.1.26
.NET version: .NET framework 4.6.2
Seems to be maybe an internal package dependency version issue or issue if the deserialization happens in a w3 process.
Has anyone faced such issues with the protobuf-net package for a REST service.
Below is the code where the ProtoDeserialize function throws a exception Serializer.Deserialize<T>(stream) is called
[ProtoContract]
public class Temp
{
[ProtoMember(1)]
public string name;
[ProtoMember(2)]
public int no;
}
[HttpGet]
public HttpResponseMessage DerserializeProtoBuf()
{
try
{
var x1 = new Temp();
x1.name = "testData";
x1.no = 10;
var data1 = ProtoSerialize<Temp>(x1);
var y = ProtoDeserialize<Temp>(data1); // throws exception
}
catch
{
}
}
public static T ProtoDeserialize<T>(byte[] data) where T : class
{
if (null == data) return null;
try
{
using (var stream = new MemoryStream(data))
{
using (var decompressor = new GZipStream(stream, CompressionMode.Decompress))
{
return Serializer.Deserialize<T>(stream); // throws Invalid wire-type error here
}
}
}
catch(Exception ex)
{
throw new InvalidDataException(String.Format("Invalid data format when proto deserializing {0}", typeof(T).Name), ex);
}
}
public static byte[] ProtoSerialize<T>(T record) where T : class
{
if (null == record) return null;
try
{
using (var stream = new MemoryStream())
{
using (var gZipStream = new GZipStream(stream, CompressionMode.Compress))
{
Serializer.Serialize(gZipStream, record);
}
return stream.ToArray();
}
}
catch(Exception ex)
{
throw new InvalidDataException(String.Format("Invalid data format when proto serializing {0}", typeof(T).Name), ex);
}
}
I have tried adding the package dependencies versions explicilty by adding bindingRedirects.
Have tried updating and degrading the version of protobuf to 2.3.7 and other before versions
Pass decompressor instead of stream to Deserialize. You're passing it the compressed gzip data instead of the decompressed protobuf payload.

Save and Load file in HoloLens using Unity editer

I'm trying to Save and Load Vector3 Coordinates in HoloLens App the program works on my laptop using unity but it will not save or load a file in the HoloLens.
Here is the program I am using to create the path for saving and loading. Any help would be appreciated.
public GameData Load()
{
string fullPath = Path.Combine(dataDirPath, dataFileName);
GameData loadedData = null;
if (File.Exists(fullPath))
{
try
{
string dataToLoad = "";
using (FileStream stream = new FileStream(fullPath, FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
dataToLoad = reader.ReadToEnd();
}
}
loadedData = JsonUtility.FromJson<GameData>(dataToLoad);
}
catch (Exception e)
{
UnityEngine.Debug.LogError("Error occured when trying to load data from filr: " + fullPath + "\n" + e);
}
}
return loadedData;
}
public void Save (GameData data)
{
string fullPath = Path.Combine(dataDirPath, dataFileName);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
string dataToStore = JsonUtility.ToJson(data, true);
using (FileStream stream = new FileStream(fullPath, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(dataToStore);
}
}
}
catch (Exception e)
{
UnityEngine.Debug.LogError("Error occured when trying to save data to file: " + fullPath + "\n" + e);
}
}
}
If I understand this correctly, you're debugging remotely. To clarify, your application cannot access files on HoloLens until you deploy it to HoloLens. And for how to access files on HoloLens, you can refer Create, write, and read a file - UWP applications | Microsoft Learn and Working with File on Hololens 2 (UWP to .NET).

CRM 2011 Online Plugin works fine but no Update committed

I'm a new developper in CRM 2011. I've made that simple code for tests.
It appears that the plugin works fine (checked with the ITracingService) but it seems that the attributes doesn't take the new values.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk;
namespace AgeUpdatePlugin
{
public class AgeUpdatePlugin:IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
try
{
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
if (tracingService == null)
throw new InvalidPluginExecutionException("Failed to retrieve the tracing service.");
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
tracingService.Trace("Plugin has started..");
//l'expression de condition
ConditionExpression condition = new ConditionExpression("new_datenaissance", ConditionOperator.NotNull);
FilterExpression filter = new FilterExpression();
filter.Conditions.Add(condition);
ColumnSet cols = new ColumnSet();
//cols.AddColumn("Id");
cols.AddColumn("new_candidatid");
cols.AddColumn("new_age");
cols.AddColumn("new_datenaissance");
QueryExpression query = new QueryExpression();
query.Criteria = filter;
query.EntityName = "new_candidat";
query.ColumnSet = cols;
tracingService.Trace("appel retrieve multiple with date=" + DateTime.Now.ToString() + "/"+DateTime.Now.ToLocalTime().ToString());
var retrieve = service.RetrieveMultiple(query).Entities;
foreach (var c in retrieve)
{
var dt =(DateTime)c.Attributes["new_datenaissance"];
tracingService.Trace(dt.ToString());
if (dt.Month == DateTime.Now.Month && dt.Day == DateTime.Now.Day)
{
tracingService.Trace((DateTime.Now.Year - DateTime.Parse(c["new_datenaissance"].ToString()).Year).ToString());
c.Attributes["new_age"] = DateTime.Now.Year - DateTime.Parse(c["new_datenaissance"].ToString()).Year;
tracingService.Trace(c.Attributes["new_candidatid"].ToString() +" - "+c.Attributes["new_age"].ToString());
service.Update(c);
tracingService.Trace("updated");
}
}
tracingService.Trace("Plugin done working");
throw new InvalidPluginExecutionException("This is from a plugin that Mehdi has created ");
}
catch (Exception exc)
{
throw exc;
}
}
}
}
Whenever you throw an exception within a plugin the transaction is aborted so you won't see your changes applied. Remove the following line:
throw new InvalidPluginExecutionException("This is from a plugin that Mehdi has created ");
I assume you added this to see the trace output which is only available when an exception is thrown. With CRM Online your best bet for tracing is to write to a custom trace entity.

List changed files in TFS but ordered by number of changes applied

Is there a way of listing all the files that have changed on a project, but ordered by the number of changes made to each file?
I want to do a code review but only from a selection of the most active files.
You may try to use Excel as a TFS reporting tool like in this blog post:
http://www.woodwardweb.com/vsts/getting_started.html
ps. I found that link in this question.
I searched different ways and finally I found that best way is using TFS API
here is the code :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace VControl
{
class Program
{
class SourceElement
{
public string filename;
public int numberOfModification;
}
static void Main(string[] args)
{
TfsTeamProjectCollection projectCollection = new
TfsTeamProjectCollection(new Uri("http://server:8080/tfs/ProjectCollection/"),
new System.Net.NetworkCredential("username", "password"));
projectCollection.EnsureAuthenticated();
Workspace workspace = null;
Boolean createdWorkspace = false;
String newFolder = String.Empty;
VersionControlServer versionControl = projectCollection.GetService<VersionControlServer>();
var teamProjects = new List<TeamProject>(versionControl.GetAllTeamProjects(false));
String workspaceName = String.Format("{0}-{1}", Environment.MachineName, "TestWorkspace");
try
{
workspace = versionControl.GetWorkspace(workspaceName, versionControl.AuthorizedUser);
}
catch (WorkspaceNotFoundException)
{
workspace = versionControl.CreateWorkspace(workspaceName, versionControl.AuthorizedUser);
createdWorkspace = true;
}
var serverFolder = String.Format("$/{0}", teamProjects[0].Name) + "/solutionFolder/";
var localFolder = Path.Combine(Path.GetTempPath(), "localFolder") + "/solutionFolder/";
var workingFolder = new WorkingFolder(serverFolder, localFolder);
// Create a workspace mapping.
workspace.CreateMapping(workingFolder);
if (!workspace.HasReadPermission)
{
throw new SecurityException(
String.Format("{0} does not have read permission for {1}",
versionControl.AuthorizedUser, serverFolder));
}
// Get the files from the repository.
workspace.Get();
string[] directories = Directory.GetDirectories(workspace.Folders[0].LocalItem);
FileStream outputFile = new FileStream("result.txt", FileMode.Create);
StreamWriter writer = new StreamWriter(outputFile);
List<SourceElement> fileLiset = new List<SourceElement>();
foreach (string dir in directories)
{
foreach (string file in Directory.GetFiles(dir))
{
string filenamae = System.IO.Path.GetFileName(file);
Item source = versionControl.GetItem(file);
System.Collections.IEnumerable history = versionControl.QueryHistory(file,
VersionSpec.Latest, 0, RecursionType.Full, null, null, null, 300, true, true, false, false);
int numberOfModification = 0;
foreach (var item in history)
numberOfModification++;
SourceElement fileElement = new SourceElement();
fileElement.filename = filenamae;
fileElement.numberOfModification = numberOfModification;
fileLiset.Add(fileElement);
}
}
var sortedList = fileLiset.OrderBy(x=> x.numberOfModification);
// Loop through keys.
foreach (var key in sortedList)
{
writer.WriteLine("{0}: {1}", key.filename, key.numberOfModification);
}
writer.Close();
}
}
}

MongoDB: Getting the list of all databases?

How do I list all databases for a connection using Mongo C# Driver?
Very easily:
var server = MongoServer.Create("mongodb://localhost/?safe=true");
var databaseNames = server.GetDatabaseNames();
The MongoServer class was deprecated in version 2.0.0.
You can use ListDatabasesAsync
using (var cursor = await client.ListDatabasesAsync())
{
await cursor.ForEachAsync(d => Console.WriteLine(d.ToString()));
}
Working Solution:
MongoClient client = new MongoClient("mongodb://localhost:27017");
using (IAsyncCursor<BsonDocument> cursor = client.ListDatabases())
{
while (cursor.MoveNext())
{
foreach (var doc in cursor.Current)
{
Console.WriteLine(doc["name"]); // database name
}
}
}
The MongoServer class was deprecated in version 2.0.0 as Juri pointed out. If you don't want to use async, here's how I do it:
var client = new MongoClient("mongodb://" + server_username + ":" + server_password + "#" + server_host + ":" + server_port);
List<MongoDB.Bson.BsonDocument> databases = client.ListDatabases();
Just one thing. It is in BsonDocument format that has 2 elements: "name" and "sizeOnDisk".
Hope this helps.
I wasn't able validate if a given DB exists or not with the existing answers, so here's my take on it:
// extension method on IMongoClient
public static IMongoClient AssertDbExists(this IMongoClient client, string dbName)
{
bool dbFound = false;
using(var cursor = client.ListDatabases())
{
var databaseDocuments = cursor.ToList();
foreach (var db in databaseDocuments)
{
if (db["name"].ToString().Equals(dbName))
{
dbFound = true;
break;
}
}
}
if (!dbFound) throw new ArgumentException("Can't connect to a specific database with the information provided", nameof(MongoSettings.ConnectionString));
return client;
}
And then use it like this:
// either you get the client with the DB validated or throws
_client = new MongoClient(settings.ConnectionString).AssertDbExists(_dbName);
Using: Mongo Official C# driver v2.4.4