Serilog mssql sink SqlColumn data type - c#

I am attempting to add an additional column to my logging in SQL Server. In the examples, they give something very similar to the following:
var columnOptions = new ColumnOptions
{
AdditionalDataColumns = new Collection<SqlColumn>
{
new SqlColumn { DataType = SqlDbType.NVarChar, DataLength = 20, ColumnName = "B" }
}
}
The problem that I am having is that my compiler keeps complaining about the SqlColumn type usage saying that it is unknown. I am using .Net 4.6.1. What do I need to add to my using? I have the following already:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using System.Net.Http.Formatting;
using Dapper;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Newtonsoft.Json.Serialization;
using Owin;
using Serilog;
using Serilog.Filters;
using Serilog.Sinks.MSSqlServer;
using SerilogWeb.Classic.WebApi;
EDIT
I have just attempted building an entire new web api project, and the following code also will not work, for some reason I cannot access the SqlColumn type. Note that the error is that the type doesn't exist on the namespace (not an error due to the constructor).
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Owin;
using Serilog;
using Serilog.Sinks.MSSqlServer;
[assembly: OwinStartup(typeof(TestProject.Startup))]
namespace TestProject
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
var x = new Serilog.Sinks.MSSqlServer.SqlColumn();
}
}
}

You will need to Update Serilog.Sinks.MSSqlServer to prereleased version 5.1.3-dev-00232 as its not exist in version 5.1.2
Install-Package Serilog.Sinks.MSSqlServer -Version 5.1.3-dev-00232
Or you can add column using DataColumn type in version 5.1.2 as below
var columnOptions = new ColumnOptions
{
AdditionalDataColumns = new Collection<DataColumn>
{
new DataColumn {DataType = typeof (string), ColumnName = "User"},
new DataColumn {DataType = typeof (string), ColumnName = "Other"},
}
};
var log = new LoggerConfiguration()
.WriteTo.MSSqlServer(#"Server=.\SQLEXPRESS;Database=LogEvents;Trusted_Connection=True;", "Logs", columnOptions: columnOptions)
.CreateLogger();

Related

Google API Client returning 404 not fund

I am trying to get the best searches from google, using keyword, and GoogleAPI, but It is always returning "System.Net.WebException: 'The remote server returned an error: (404) Not Found.'"
Am I doing anything wrong, or is it that GoogleAPI is outdated? Last time I checked and downloaded the .dll file was from 2010...
code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using Microsoft.Win32;
using System.Web;
using System.Net.Mail;
using System.Net.Mime;
using System.ComponentModel;
using System.Net;
using System.Windows;
using Google.Apis.Services;
using Google.Apis.CustomSearchAPI.v1;
//Ignore most using statements, It was imported from my previous code.
namespace TYZDsag
{
internal class Program
{
static void Main(string[] args)
{
var client = new Google.API.Search.GwebSearchClient("https://www.google.com/");
var results = client.Search("uhuhuh", 12);
foreach (var webResult in results)
{
Console.WriteLine("{0}, {1}, {2}", webResult.Title, webResult.Url, webResult.Content);
//listBox1.Items.Add(webResult.ToString());
}
}
}
}
That's not how you initialize a service object using an api key.
using System;
using System.Threading.Tasks;
using Google.Apis.CustomSearchAPI.v1;
using Google.Apis.Services;
namespace customsearch
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
var service = new CustomSearchAPIService(new BaseClientService.Initializer()
{
ApiKey = "XXX",
ApplicationName = "xyz",
});
var result = await service.Cse.List().ExecuteAsync();
}
}
}
Method: cse.list
How to create an api key

How to send a simple message using a twilio number with an ASP.NET MVC project?

I am trying to change and edit the code but it returns with exceptions errors in regards authentication errors. The username cannot be null as well as the category is not able to load the code. Another exception that is running on it is the Twilio.Exceptions.ApiExecution that requires a phone number.
The documentation is here: https://www.twilio.com/docs/sms/tutorials/server-notifications-csharp-mvc?code-sample=code-csv-list-of-phone-numbers-to-notify&code-language=csv&code-sdk-version=default
The video to build the code for integrating Twilio in an ASP.net MVC project is here: https://www.youtube.com/watch?v=ndxQXnoDIj8
The code excerpt is here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
using Twilio.TwiML;
using Twilio.AspNet.Mvc;
namespace SendandReceiveSms.Controllers
{
public class SMSController : TwilioController
{
// GET: SMS
public ActionResult SendSms()
{
var accountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
var authToken = ConfigurationManager.AppSettings["TwilioAuthToken"];
TwilioClient.Init("ACa4XXXXXXXXXX","77XXXXXXXXXX");
var to = new PhoneNumber(ConfigurationManager.AppSettings["+65XXXXXXXX"]);
var from = new PhoneNumber("+12053016835");
var message = MessageResource.Create(
to: to,
from: from,
body: "Conserve with us and save the Wolrd ");
return Content(message.Sid);
}
public ActionResult ReceiveSms()
{
var response = new MessagingResponse();
response.Message(" We turn waste into environmental assets");
return TwiML(response);
}
}
}
You can try this also.
using DocGen.Notifications.Contract;
using DocGen.Notifications.Models;
using System;
using System.Configuration;
using System.Linq;
using System.Text;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace DocGen.Notifications.Providers
{
public class SmsNotificationProvider : INotificationProtocolContract
{
NotificationResponseModel notificationResponseModel = new NotificationResponseModel();
public NotificationResponseModel SendNotification(NotificationRequestModel notificationRequestModel)
{
if (notificationRequestModel.SmsTo == null || notificationRequestModel.SmsTo.Count() == 0)
throw new ArgumentNullException(nameof(notificationRequestModel.SmsTo));
TwilioClient.Init(ConfigurationManager.AppSettings["accountSid"], ConfigurationManager.AppSettings["authToken"]);
foreach (var Sms_to in notificationRequestModel.SmsTo)
{
var to = new PhoneNumber(Sms_to);
var message = MessageResource.Create(
to,
from: new PhoneNumber(ConfigurationManager.AppSettings["senderNumber"]),//"+12563054795"
body: Encoding.UTF8.GetString(notificationRequestModel.Message));
notificationResponseModel.ResponseMessage = message.Status.ToString();
}
//notificationResponseModel.ResponseMessage = "Message Successfully sent.";
return notificationResponseModel;
}
}
}

"Can't find" NS*Types (eg. NSFileManager or NSUrl) in Xamarin Forms project

I get "Not Found" errors in Xamarin Forms with things like NSFileManager and NSUrl. These are my imports of my class where I'm getting these errors:
using System;
using System.IO;
using System.Reflection;
using DrinkUp.Controls;
using DrinkUp.iOS.Renderers;
using MediaPlayer;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
And the class which I'm using is located in DrinkUp.iOS.
Whenever and wherever I type something with the NS prefix it says that it could not find the object. Can someone please tell me what I'm doing wrong here?
Here's my full class
using System;
using System.IO;
using System.Reflection;
using DrinkUp.Controls;
using DrinkUp.iOS.Renderers;
using MediaPlayer;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(Video), typeof(VideoRenderer))]
namespace DrinkUp.iOS.Renderers
{
public class VideoRenderer : ViewRenderer<Video, UIView>
{
MPMoviePlayerController videoPlayer;
object notification = null;
void InitVideoPlayer()
{
var path = Path.Combine(NSBundle.MainBundle.BundlePath, Element.Source);
if (!NSFileManager.DefaultManager.FileExists(path)) {
Console.WriteLine("Video not exist");
videoPlayer = new MPMoviePlayerController();
videoPlayer.ControlStyle = MPMovieControlStyle.None;
videoPlayer.ScalingMode = MPMovieScalingMode.AspectFill;
videoPlayer.RepeatMode = MPMovieRepeatMode.One;
videoPlayer.View.BackgroundColor = UIColor.Clear;
SetNativeControl(videoPlayer.View);
return;
}
// Load the video from the app bundle.
NSUrl videoURL = new NUrl(path, false);
// Create and configure the movie player.
videoPlayer = new MPMoviePlayerController(videoURL);
videoPlayer.ControlStyle = MPMovieControlStyle.None;
videoPlayer.ScalingMode = MPMovieScalingMode.AspectFill;
videoPlayer.RepeatMode = Element.Loop ? MPMovieRepeatMode.One : MPMovieRepeatMode.None;
videoPlayer.View.BackgroundColor = UIColor.Clear;
foreach (UIView subView in videoPlayer.View.Subviews) {
subView.BackgroundColor = UIColor.Clear;
}
videoPlayer.PrepareToPlay();
SetNativeControl(videoPlayer.View);
}
}
}
The first comment worked, I had to get the NS types from Foundation.
Like Foundation.NSUrl etc. This fixed my problem.

SQLite Xamarin.Forms PCL errors on Android

I am trying to build an sqlite database on xamarin(C#) in pcl project. I am following this tutorial. On the Android Implementation (Step5) i get these errors:
Error CS0104 'Environment' is an ambiguous reference between 'Android.OS.Environment' and 'System.Environment' AlarmSQLite.Android c:\users\thomas\source\repos\AlarmSQLite\AlarmSQLite\AlarmSQLite.Android\SQLite_Android.cs 30 Active
Error CS0234 The type or namespace name 'Net' does not exist in the namespace 'SQLite' (are you missing an assembly reference?) AlarmSQLite.Android c:\users\thomas\source\repos\AlarmSQLite\AlarmSQLite\AlarmSQLite.Android\SQLite_Android.cs 33 Active
I use VisualStudio2017. I tried to remove .Net and added System.Environment but i get more and new errors.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using SQLite;
using Xamarin.Forms;
using AlarmSQLite.Droid;
using System.IO;
[assembly: Dependency(typeof(SQLite_Android))]
namespace AlarmSQLite.Droid
{
public class SQLite_Android : ISQLite
{
public SQLite_Android() { }
public SQLite.SQLiteConnection GetConnection()
{
var dbName = "AlarmDB.db3";
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsPath, dbName);
var platform = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
var connection = new SQLite.Net.SQLiteConnection(platform, path);
return connection;
}
}
}
Everything is the same with the tutorial. What am i doing wrong? Thank you!
New Errors:
Error CS0234 The type or namespace name 'Platform' does not exist in the namespace 'SQLite' (are you missing an assembly reference?) AlarmSQLite.Android C:\Users\Thomas\source\repos\AlarmSQLite\AlarmSQLite\AlarmSQLite.Android\SQLite_Android.cs 33 Active
Error CS0029 Cannot implicitly convert type 'SQLite.Net.SQLiteConnection' to 'SQLite.SQLiteConnection' AlarmSQLite.Android C:\Users\Thomas\source\repos\AlarmSQLite\AlarmSQLite\AlarmSQLite.Android\SQLite_Android.cs 36 Active
Error CS0104:
Environment comes from 'Android.OS.Environment' as well as 'System.Environment' so giving you and ambiguity issue. Just Prepend System to the Environment.
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
Error CS0234: Seems like you haven't added SQLite-Async Nuget Package. You have to add this in your PCL as well as in Android project and build project again.
Error CS0234 & CS0029: Make sure you added following two nuget packages in android and pcl projects.
Then, instead of using Sqlite, try to use Sqlite.Net.
Your Final Code should Look :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using AlarmSQLite.Droid;
using System.IO;
using SQLite.Net;
using SQLite.Net.Async;
[assembly: Dependency(typeof(SQLite_Android))]
namespace AlarmSQLite.Droid
{
public class SQLite_Android : ISQLite
{
public SQLite_Android() { }
public SQLiteConnection GetConnection()
{
var dbName = "AlarmDB.db3";
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsPath, dbName);
var platform = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
var connection = new SQLiteConnection(platform, path);
return connection;
}
}
}
Do not forget to adjust your interface for the same. It should be like:
SQLiteConnection GetConnection():
Note: You can omit Sqlite.Net.Async PCL reference if you don't need it.

Error compiling delegate and dispatcher

I'm new to the threading world and trying to make my application works with threads. Here is what I got:
public static void ThreadProc()
{
Thread.Sleep(500);
MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("SuperMMFofDoom", MemoryMappedFileRights.ReadWrite);
MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(0, sizeof(double)*3 + sizeof(int) *2);
Image imgS = new Image();
ImageTrigger myMessage;
Mutex imgMutex = new Mutex(false, "imgMutex");
while (threadRunning)
{
imgMutex.WaitOne();
accessor.Read(0, out myMessage);
// [...]
Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(delegate()
{
// [...]
}),
new object[] { imgS, myMessage.performance }
);
imgMutex.ReleaseMutex();
}
}
This thing does compile when I comment all the Dispatcher.Invoke(). If I don't, I get an error about System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority, System.Delegate, object) and it does not compile.
Any ideas?
I'm using VS2010 on Windows 7 Pro x64. This is a C# WPF project which also make use of some C++ DLLs also compiled in the same project. Finally, here is the header of the file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Threading;
using System.IO.MemoryMappedFiles;
using Common;
You should not be creating a new Action just casting your delegate as one:
Async:
Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)delegate()
{
});
Sync:
Dispatcher.Invoke(DispatcherPriority.Background, (Action)delegate()
{
});
Or if your not on a control or window:
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, (Action)delegate()
{
});

Categories

Resources