I'm following this tutorial and I'm stuck at the part where the TwitterAcces class (that contains the twitter token) is serialized. This is where the serialization method is called:
void CallBackVerifiedResponse(OAuthAccessToken at, TwitterResponse response)
{
if (at != null)
{
SerializeHelper.SaveSetting<TwitterAccess>("TwitterAccess", new TwitterAccess
{
AccessToken = at.Token,
AccessTokenSecret = at.TokenSecret,
ScreenName = at.ScreenName,
UserId = at.UserId.ToString()
});
}
}
And this is my SerializeHelper.cs:
public class SerializeHelper
{
public static void SaveSetting<T>(string fileName, T dataToSave)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
using (var stream = store.CreateFile(fileName))
{
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(stream, dataToSave);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return;
}
}
}
}
The error I'm getting is: The type or namespace name 'DataContractSerializer' could not be found (are you missing a using directive or an assembly reference?) Visual Studio can't help me resolve the problem. It suggests creating a new class. I googled around and I think the class should be inside System.Runtime.Serialization; which I am using but that doesn't solve the problem.
You got to add System.Runtime.Serialization.dll referenced in your project.
Related
Summary:
My GraphQL ExecuteAsync returns a result that contains. According to the stackTrace provided below, the system cannot resolve my custom type remitsGeneralSearch. The remitsGeneralSearch resolver can return a type called ClaimPaymentOrCheckSearchGraphType which is a UnionGraphType.
StackTrace:
["GraphQL.ExecutionError: Error trying to resolve remitsGeneralSearch.\n ---> System.InvalidOperationException: Unexpected type: \n at GraphQL.Execution.ExecutionStrategy.BuildExecutionNode(ExecutionNode parent, IGraphType graphType, Field field, FieldType fieldDefinition, String[] path)\n at GraphQL.Execution.ExecutionStrategy.SetSubFieldNodes(ExecutionContext context, ObjectExecutionNode parent, Dictionary`2 fields)\n at GraphQL.Execution.ExecutionStrategy.SetSubFieldNodes(ExecutionContext context, ObjectExecutionNode parent)\n at GraphQL.Execution.ExecutionStrategy.ExecuteNodeAsync(ExecutionContext context, ExecutionNode node)\n --- End of inner exception stack trace ---"]4008305)
GraphQL Version: 2.4.0
FrameWork: .Net
OS: MacOS Catalina
Links Referenced: https://github.com/graphql-dotnet/graphql-dotnet/issues/964
CODE SNIPPETS:
RESOLVER:
FieldAsync<ClaimPaymentOrCheckSearchGraphType>(
"remitsGeneralSearch",
resolve: async context =>
{
var securityFilter = await GetUserRemitFilters(context);
var range = context.GetRange();
var sortFields = context.GetArgument<List<SortField>>("sort") ?? Enumerable.Empty<SortField>();
var whereClaimPayment = context.GetArgument<ClaimPaymentSearchFilter>("whereClaimPayment");
Connection<ClaimPaymentSearchRow> claimPaymentSearchRowResult;
try
{
using (LogContext.PushProperty("where", whereClaimPayment, true))
{
//claimPaymentSearchRowResult = await DMAQueryService.GetRemitReadersAsync(context);
var whereArguments = context.Arguments["whereClaimPayment"] as Dictionary<string, object>;
claimPaymentSearchRowResult = await DMAQueryService.GetRemitReadersAsync(
range,
whereClaimPayment,
whereArguments,
sortFields,
securityFilter,
context.CancellationToken
);
}
}
catch (Exception e)
{
_logger.LogInformation("Exception occurred {e}", e);
throw e;
}
var userRemitFilters = context.UserContext as Services.DMA.UserRemitFilters;
if (claimPaymentSearchRowResult.EdgeCount > 0)
{
return claimPaymentSearchRowResult;
}
var _whereCheckSearch = context.GetArgument<CheckSearchFilter>("whereCheck");
try
{
Connection<CheckSearchRow> checkSearchRowResult;
using (LogContext.PushProperty("whereCheck", _whereCheckSearch, true))
{
checkSearchRowResult = await DMAQueryService.GetCheckReadersAsync(context);
return checkSearchRowResult;
}
}
catch (Exception e)
{
throw e;
}
},arguments: queryArguments
);
}
catch (Exception e)
{
throw e;
}
Custom GraphType:
[Transient]
public class ClaimPaymentOrCheckSearchGraphType : UnionGraphType
{
private readonly ILogger<ClaimPaymentOrCheckSearchGraphType> _logger;
public ClaimPaymentOrCheckSearchGraphType(
ILogger<ClaimPaymentOrCheckSearchGraphType> logger,
ConnectionGraphType<ClaimPaymentSearchGraphType> claimPaymentSearchGraphType,
ConnectionGraphType<CheckSearchGraphType> checkSearchGraphType
)
{
_logger = logger;
Type<ConnectionGraphType<ClaimPaymentSearchGraphType>>();
Type<ConnectionGraphType<CheckSearchGraphType>>();
ResolveType = obj =>
{
try
{
if (obj is Connection<ClaimPaymentSearchRow>)
{
return claimPaymentSearchGraphType;
}
if (obj is Connection<CheckSearchRow>)
{
return checkSearchGraphType;
}
throw new ArgumentOutOfRangeException($"Could not resolve graph type for {obj.GetType().Name}");
}
catch (Exception e)
{
_logger.LogInformation("ClaimPaymentOrCheckSearchGraphType Exception {e}: ", e);
throw e;
}
};
}
}
Link to answer found here: https://github.com/graphql-dotnet/graphql-dotnet/issues/2674Try replacing this:
Type<ConnectionGraphType<ClaimPaymentSearchGraphType>>();
Type<ConnectionGraphType<CheckSearchGraphType>>();
with this:
AddPossibleType(claimPaymentSearchGraphType);
AddPossibleType(checkSearchGraphType);
I'm thinking that if you're registering these types as transients, then the copy that gets registered to the schema initialization code is a different copy that gets returned from ResolveType. Because of that, its fields' ResolvedType properties was never set, and so null is passed into BuildExecutionNode for the graphType instead of a resolved type.
If the ResolveType method could return a type rather than an instance, there wouldn't be an issue, but unfortunately that's not the way it works. Or you could register the type as a singleton.
I have this problem on a asp.net website, but it should be general for .Net Core on windows computer.
If I try to translate an nonexistent Domain, I’ll get an exception, it’s OK, but then, all next calls with correct domain name throw an exception also "System.ObjectDisposedException: Safe handle has been closed".
I'm asking about some workaround, because name translation does ‘not work until restart of application.
This behavior can be reproduced with
Microsoft.NETCore.App 2.2.0
System.Security.Principal.Windows 4.5.1
class Program
{
static string Translate(string gName)
{
try
{
var nt = new NTAccount(gName);
if (nt.IsValidTargetType(typeof(SecurityIdentifier)))
{
var si = (SecurityIdentifier)(nt).Translate(typeof(SecurityIdentifier));
return si.ToString();
}
}
catch (Exception ex)
{
Console.Write(ex.ToString()+"\n\n");
}
return "";
}
static void Main(string[] args)
{
var si= new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
var na = si.Translate(typeof(NTAccount));
var knownName = na.ToString();
foreach (var aName in new[] { knownName,
#"DOMAIN_NOT_ESISTS\Benutzer",
knownName })
{
Console.WriteLine(aName);
Console.WriteLine(Translate(aName));
}
Console.ReadKey();
}
}
hello I downloaded the solution nopCommerce an e-commerce open source which achievement operate and install without problems with MSSQLSERVER database however I would like to implement with ORACLEdatabase
Official Site http://www.nopcommerce.com/
I have been guiding me this post
http://www.nopcommerce.com/boards/t/17712/mysql-support.aspx
I have tried to follow the steps indicated for mysql and adapt to oracle yet one of the first things that tells me is the creation of two classes
OracleConnectionFactory:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity.Infrastructure;
using System.Data.Common;
using Oracle.DataAccess.Client;
namespace Nop.Data
{
public class OracleConnectionFactory : IDbConnectionFactory
{
private readonly string _baseConnectionString;
private Func<string, DbProviderFactory> _providerFactoryCreator;
public OracleConnectionFactory()
{
}
public OracleConnectionFactory(string baseConnectionString)
{
this._baseConnectionString = baseConnectionString;
}
public DbConnection CreateConnection(string nameOrConnectionString)
{
string connectionString = nameOrConnectionString;
bool treatAsConnectionString = nameOrConnectionString.IndexOf('=') >= 0;
if (!treatAsConnectionString)
{
OracleConnectionStringBuilder builder = new OracleConnectionStringBuilder(this.BaseConnectionString);
//MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(this.BaseConnectionString);
//builder.Server = nameOrConnectionString;
connectionString = builder.ConnectionString;
}
DbConnection connection = null;
try
{
connection = this.ProviderFactory("Oracle.DataAccess.Client").CreateConnection();
connection.ConnectionString = connectionString;
}
catch
{
//connection = new MySqlConnection(connectionString);
connection = new OracleConnection(connectionString);
}
return connection;
}
public string BaseConnectionString
{
get
{
return this._baseConnectionString;
}
}
internal Func<string, DbProviderFactory> ProviderFactory
{
get
{
Func<string, DbProviderFactory> func1 = this._providerFactoryCreator;
return delegate(string name)
{
return DbProviderFactories.GetFactory(name);
};
}
set
{
this._providerFactoryCreator = value;
}
}
}
}
OracleProvider :
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web.Hosting;
using Nop.Data.Initializers;
using Oracle.DataAccess.Client;
using Nop.Core.Data;
namespace Nop.Data
{
public class OracleDataProvider : IDataProvider
{
#region Utilities
protected virtual string[] ParseCommands(string filePath, bool throwExceptionIfNonExists)
{
if (!File.Exists(filePath))
{
if (throwExceptionIfNonExists)
throw new ArgumentException(string.Format("Specified file doesn't exist - {0}", filePath));
else
return new string[0];
}
var statements = new List<string>();
using (var stream = File.OpenRead(filePath))
using (var reader = new StreamReader(stream))
{
var statement = "";
while ((statement = readNextStatementFromStream(reader)) != null)
{
statements.Add(statement);
}
}
return statements.ToArray();
}
protected virtual string readNextStatementFromStream(StreamReader reader)
{
var sb = new StringBuilder();
string lineOfText;
while (true)
{
lineOfText = reader.ReadLine();
if (lineOfText == null)
{
if (sb.Length > 0)
return sb.ToString();
else
return null;
}
//MySql doesn't support GO, so just use a commented out GO as the separator
if (lineOfText.TrimEnd().ToUpper() == "-- GO")
break;
sb.Append(lineOfText + Environment.NewLine);
}
return sb.ToString();
}
#endregion
#region Methods
public virtual void InitConnectionFactory()
{
//var connectionFactory = new SqlConnectionFactory();
var connectionFactory = new OracleConnectionFactory();
//TODO fix compilation warning (below)
#pragma warning disable 0618
Database.DefaultConnectionFactory = connectionFactory;
}
/// <summary>
/// Initialize database
/// </summary>
public virtual void InitDatabase()
{
InitConnectionFactory();
SetDatabaseInitializer();
}
/// <summary>
/// Set database initializer
/// </summary>
public virtual void SetDatabaseInitializer()
{
//pass some table names to ensure that we have nopCommerce 2.X installed
var tablesToValidate = new[] { "Customer", "Discount", "Order", "Product", "ShoppingCartItem" };
//custom commands (stored proedures, indexes)
var customCommands = new List<string>();
//use webHelper.MapPath instead of HostingEnvironment.MapPath which is not available in unit tests
customCommands.AddRange(ParseCommands(HostingEnvironment.MapPath("~/App_Data/Install/SqlServer.Indexes.sql"), false));
//use webHelper.MapPath instead of HostingEnvironment.MapPath which is not available in unit tests
customCommands.AddRange(ParseCommands(HostingEnvironment.MapPath("~/App_Data/Install/SqlServer.StoredProcedures.sql"), false));
var initializer = new CreateTablesIfNotExist<NopObjectContext>(tablesToValidate, customCommands.ToArray());
Database.SetInitializer(initializer);
}
/// <summary>
/// A value indicating whether this data provider supports stored procedures
/// </summary>
public virtual bool StoredProceduredSupported
{
get { return true; }
}
/// <summary>
/// Gets a support database parameter object (used by stored procedures)
/// </summary>
/// <returns>Parameter</returns>
public virtual DbParameter GetParameter()
{
//return new SqlParameter();
return new OracleParameter();
}
#endregion
}
}
also i installed the managed nuget package like this link said
http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/CodeFirst/index.html
oracle odp.net managed driver
in nop.data and nop.web
I appreciate any help freshened up the steps I need to do or that I may be going
one of the first thing i trying is the Oracle provider recognize and achieve connect to my database
It was an interesting question. Using nop commerce with Oracle is technically possible, but it would be a very wild ride for you.
Good news first. Nop Commerce is architectured based on repository pattern. Basically Nop.Data abstracts all the SQL Server related data access. You would need to re-write this almost entirely.
Not so good news next. Search, Paging, Catalog listing uses a stored procedure in SQL Server. You may need to re-write it completely. And most of the time, you are on your own. Unless if you are confident with Oracle and .Net EF, it would be a really wild ride.
I would say, its less problem if you want to stick with SQL Server. I understand sometime you may not make technical decision. So you can explain clearly about complexity and effort needed to migrate to the person makes that decision.
Source: NopCommerce developer for last 2.5years.
I'm doing a console application in Visual Studio, but I have a little problem.
If I want to open a browser with a specified URL when any key is pressed, how can I do that?
Thanks
If you want to cover also .Net Core applications.Thanks to Brock Allen
https://brockallen.com/2016/09/24/process-start-for-urls-on-net-core/
public static void OpenBrowser(string url)
{
try
{
Process.Start(url);
}
catch
{
// hack because of this: https://github.com/dotnet/corefx/issues/10361
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
url = url.Replace("&", "^&");
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw;
}
}
}
Use the ProcessStartInfo class instance to set of values that are used to start a process.
Something like this:
using System;
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var psi = new ProcessStartInfo("iexplore.exe");
psi.Arguments = "http://www.google.com/";
Process.Start(psi);
}
}
}
this is a somewhat exotic question but I will try anyway.
I am writing a Visual Studio 2010 Extension using MEF. At some point in my code, I am required to provide some error glyphs ( like brakepoints ) whenever a document is saved. The problem is that I can't seem to find how to force GetTags of my ITagger to be called without having the user writing anything.
I can catch the document save event but I am missing the "link" between this and somehow getting GetTags method to be called. Any ideas?
Here is some code :
internal class RTextErrorTag : IGlyphTag
{}
class RTextErrorGlyphTagger : ITagger<RTextErrorTag>
{
private IClassifier mClassifier;
private SimpleTagger<ErrorTag> mSquiggleTagger;
private EnvDTE._DTE mMSVSInstance = null;
private List<object> mDTEEvents = new List<object>();
internal RTextErrorGlyphTagger(IClassifier classifier, IErrorProviderFactory squiggleProviderFactory, ITextBuffer buffer, IServiceProvider serviceProvider)
{
this.mClassifier = classifier;
this.mSquiggleTagger = squiggleProviderFactory.GetErrorTagger(buffer);
mMSVSInstance = serviceProvider.GetService(typeof(EnvDTE._DTE)) as EnvDTE._DTE;
var eventHolder = mMSVSInstance.Events.DocumentEvents;
mDTEEvents.Add(eventHolder);
eventHolder.DocumentSaved += new EnvDTE._dispDocumentEvents_DocumentSavedEventHandler(OnDocumentSaved);
}
void OnDocumentSaved(EnvDTE.Document Document)
{
//fire up event to renew glyphs - how to force GetTags method?
var temp = this.TagsChanged;
if (temp != null)
temp(this, new SnapshotSpanEventArgs(new SnapshotSpan() )); //how to foce get
}
IEnumerable<ITagSpan<RTextErrorTag>> ITagger<RTextErrorTag>.GetTags(NormalizedSnapshotSpanCollection spans)
{
foreach (SnapshotSpan span in spans)
{
foreach (var error in this.mSquiggleTagger.GetTaggedSpans(span))
{
yield return new TagSpan<RTextErrorTag>(new SnapshotSpan(span.Start, 1), new RTextErrorTag());
}
}
}
public event EventHandler<SnapshotSpanEventArgs> TagsChanged;
}