Serilog WriteTo.MSSqlServer Not working Console (Not Core) - serilog

I'm having issues with WriteTo.MSSqlServer not wring to the configured database. AutitTo.MSSqlServer work fine. This is in a console app, C#. Not Core.
I've looked all over and everything I've found is a dead end. Getting a little frustrated
Code:
var sinkOptions = new SinkOptions() {
TableName = "Logs",
AutoCreateSqlTable = true,
SchemaName = "dbo"
};
//Create/Configure the logger
_logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File(#"C:\Users\c.clover\source\repos\ConsoleApp3\ConsoleApp3\Log.txt")
.WriteTo.MSSqlServer(
"Server=TEST01;Database=LogDb;Trusted_Connection=True;",
sinkOptions,
null,
null,
Serilog.Events.LogEventLevel.Information
)
.AuditTo.MSSqlServer(
"Server=TEST01;Database=LogDb;Trusted_Connection=True;",
sinkOptions,
null,
null,
Serilog.Events.LogEventLevel.Information
)
.CreateLogger();
//Log something
_logger.Information("Test Log {Now}", DateTime.Now);
Log.CloseAndFlush();
}
}

I fixed the problem by bagging ILogger _logger and using Log instead
Log.Logger = new LoggerConfiguration()... etc
Log.Information.... etc.
Log.CloseAndFlush();
What I dont get is why it doesnt work with ILogger?

Related

Can't get serilog to log to sqlserver

Help
Why can't I get serilog to log to sqlserver
I have used forever to get this to work
It logs fine to the console
I have installed the nuget packages
Serilog
Serilog.Sinks.Console
Serilog.Sinks.MSSqlServer
//First a quick test if the connection string works (db can open, and if the table exists, it works but no rows
var connection = new ConnectionStringSettings();
connection.ConnectionString = "Data Source=server-name;Initial Catalog=db-name;Persist Security Info=True;User ID=user-name;Password='password-name'";
var sqlc = new SqlConnection(connection.ConnectionString);
string query = "select * from LogEvents";
sqlc.Open();
using (var command = new SqlCommand(query, sqlc))
{
var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
}
}
reader.Close();
}
sqlc.Close();
var log = new LoggerConfiguration()
.WriteTo
.MSSqlServer(
connectionString: connection.ConnectionString,
sinkOptions: new MSSqlServerSinkOptions { TableName = "LogEvents", AutoCreateSqlTable = true }
)
.WriteTo.Console()
.CreateLogger();
Log.Logger = log;
Log.Information("123");
Log.CloseAndFlush();
Console.WriteLine("Hello, World!");

Cookies problem using web application asp net core

I am working with a shopping cart application. I have developed an application that maintains user shopping carts using cookies. It was working perfectly until I have made some UI changes and now it is not working now I have no clue what I have done wrong because I am maintaining the cookies through c# backend code no interruption with the front end only reading these cookies and passing them into view model to show on cart panel. Here is my code
Startup.cs
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
Adding Items to Cart
public JsonResult AddToShoppingCart(UserProductVM model)
{
try
{
if (string.IsNullOrEmpty(model.SelectedSize))
return Json(new { status = false, msg = "Please select size to proceed." });
var result = ShoppingCartHelper.GetShoppingCartList(model, _httpContextAccessor);
if (result.Status <= 0)
return Json(new { status = false, msg = result.Message });
Response.Cookies.Delete("ShoppingCart");
Response.Cookies.Append("ShoppingCart", JsonConvert.SerializeObject(result.Data));
return Json(new { status = true, msg = "Success! added to shopping cart." });
}
catch (Exception ex)
{
return Json(new { status = false, msg = ex.Message.ToString() });
}
}
Reading From Cart
public static string GetShoppingCartFromCookies(IHttpContextAccessor _httpContextAccessor)
{
return _httpContextAccessor.HttpContext?.Request?.Cookies["ShoppingCart"]?.ToString();
}
Every Thing was working fine and now nothing works no cookies are added to the cookies list. This is the same code I have also the backup my application and when I run that application cookies are working perfectly but the problem is that it is with the old design I am not using that UI design anymore. This is the same code working in one application but not working with another application with a different UI.
Have you added the IHttpContextAccessor to dependency container ?
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
I have resolved my issue. The problem was basically I was adding base64 image string which was not working. When I comment on this line it worked perfectly no need to change any code.
public static GenericResponseDTO<List<ShoppingCartViewModel>> GetShoppingCartList(UserProductVM model, IHttpContextAccessor _httpContextAccessor)
{
var shoppingcartmodel = new List<ShoppingCartViewModel>();
var cartmodel = new ShoppingCartViewModel
{
RestaurantId = model.RestaurantId,
SubCategoryId = model.SubCategoryId,
RestaurantSubCategoryId = model.RestaurantSubCategoryId,
OrderGuid = Guid.NewGuid(),
Quantity = model.Quantity,
//ItemImage = model.ItemImage,
SelectedSize = model.SelectedSize.Split('-')[0],
SingleItemPrice = Convert.ToDecimal(model.SelectedSize.Split('-')[1]),
SubCategoryName = model.SubCategoryName,
TotalItemPrice = (model.Quantity * Convert.ToDecimal(model.SelectedSize.Split('-')[1]))
};
if (string.IsNullOrEmpty(GetShoppingCartFromCookies(_httpContextAccessor)))
shoppingcartmodel.Add(cartmodel);
else
{
shoppingcartmodel = JsonConvert.DeserializeObject<List<ShoppingCartViewModel>>(GetShoppingCartFromCookies(_httpContextAccessor));
if (shoppingcartmodel.Any(x => x.RestaurantSubCategoryId == model.RestaurantSubCategoryId))
return new GenericResponseDTO<List<ShoppingCartViewModel>> { Data = new List<ShoppingCartViewModel>(), Status = -1, Message = "Item is alreay exists in your cart please remove and add another." };
shoppingcartmodel.Add(cartmodel);
}
return new GenericResponseDTO<List<ShoppingCartViewModel>> { Data = shoppingcartmodel, Status = 1 };
}
I have commented on the ItemImage line and it works like a charm. Maybe it helps someone else problem.

Can milo generate the cutomized datatype using uamodeler/

I have tried milo, but I found it hard to create the data object one by one.
Can milo just generate the corresponding codes by reading the xml files? And how?
Many Thanks!
yes you can
private void addCustomStructTypeVariable(UaFolderNode rootFolder) throws Exception {
NodeId dataTypeId = CustomStructType.TYPE_ID
.localOrThrow(getServer().getNamespaceTable());
NodeId binaryEncodingId = CustomStructType.BINARY_ENCODING_ID
.localOrThrow(getServer().getNamespaceTable());
UaVariableNode customStructTypeVariable = UaVariableNode.builder(getNodeContext())
.setNodeId(newNodeId("HelloWorld/CustomStructTypeVariable"))
.setAccessLevel(AccessLevel.READ_WRITE)
.setUserAccessLevel(AccessLevel.READ_WRITE)
.setBrowseName(newQualifiedName("CustomStructTypeVariable"))
.setDisplayName(LocalizedText.english("CustomStructTypeVariable"))
.setDataType(dataTypeId)
.setTypeDefinition(Identifiers.BaseDataVariableType)
.build();
CustomStructType value = new CustomStructType(
"foo",
uint(42),
true
);
ExtensionObject xo = ExtensionObject.encodeDefaultBinary(
getServer().getSerializationContext(),
value,
binaryEncodingId
);
customStructTypeVariable.setValue(new DataValue(new Variant(xo)));
getNodeManager().addNode(customStructTypeVariable);
customStructTypeVariable.addReference(new Reference(
customStructTypeVariable.getNodeId(),
Identifiers.Organizes,
rootFolder.getNodeId().expanded(),
false
));
}

Avro serialization hanging on DataFileWriter close method

I am trying to use avro serialization but when I have multiple records to serialize, the application hangs on DataFileWriter close method, however it works with a small amount of records.
final PipedOutputStream pipedOutputStream = new PipedOutputStream();
PipedInputStream pipedInputStream = new PipedInputStream(
pipedOutputStream);
DatumWriter<DW> userDatumWriter = new SpecificDatumWriter<DW>(DW.class);
DataFileWriter<DW> dataFileWriter = new DataFileWriter<DW>(
userDatumWriter);
dataFileWriter.create(payload.get(0).getSchema(), pipedOutputStream);
for (DW currentRecord : payload) {
dataFileWriter.append(currentRecord);
}
dataFileWriter.close();
return pipedInputStream;
I tried to flush after adding 10 records at a time, but then it hangs on the flush method.
Can anyone help me with this?
Solved by returning a ByteArrayOutputStream as follows:
Schema schema = ReflectData.get().getSchema(DW.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ReflectDatumWriter<Object> reflectDatumWriter = new ReflectDatumWriter<Object>(
schema);
DataFileWriter<Object> writer = new DataFileWriter<Object>(
reflectDatumWriter).create(schema, outputStream);
for (DW currentRecord : payload) {
writer.append(currentRecord);
}
writer.close();
return outputStream.toByteArray();

Error 401 authenticating with Project Online and CSOM

I get error 401 (or 403) when trying to connect to Project Online with CSOM in a console app. (This is not on-premise. It is Microsoft Project Online 2013.) Here is the code.
ProjectContext projContext = new ProjectContext(pwaPath);
projContext.Credentials = new NetworkCredential("myUserID", "mypwd", "xxx.onmicrosoft.com");
projContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(projContext_ExecutingWebRequest);
projContext.Load(projContext.Projects);
projContext.ExecuteQuery();
**// Error 401 Unauthorized**
static void projContext_ExecutingWebRequest(object sender, WebRequestEventArgs e)
{
e.WebRequestExecutor.WebRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
}
And another try, without ExecutingWebRequest:
ProjectContext projContext = new ProjectContext(pwaPath);
projContext.Credentials = new NetworkCredential("myUserID", "mypwd", "xxx.onmicrosoft.com");
projContext.Load(projContext.Projects);
projContext.ExecuteQuery();
**// Error 403 Forbidden**
Q1: Are there any problems with the code?
Q2: Is there a setting in Project Online that I'm missing?
You can use:
new SharePointOnlineCredentials(username, secpassword);
instead of
new NetworkCredential("admin#myserver.onmicrosoft.com", "password");
First: Install required Client SDK
SharePoint Client SDK :
http://www.microsoft.com/en-au/download/details.aspx?id=35585
Project 2013 SDK:
http://www.microsoft.com/en-au/download/details.aspx?id=30435
Second: add the reference to your project
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
Microsoft.ProjectServer.Client.dll
You can find the dlls in %programfiles%\Common Files\microsoft shared\Web Server Extensions\15\ISAPI
and %programfiles(x86)%\Microsoft SDKs\Project 2013\REDIST
Here is sample code:
using System;
using System.Security;
using Microsoft.ProjectServer.Client;
using Microsoft.SharePoint.Client;
public class Program
{
private const string pwaPath = "https://[yoursitehere].sharepoint.com/sites/pwa";
private const string username ="[username]";
private const string password = "[password]";
static void Main(string[] args)
{
SecureString secpassword = new SecureString();
foreach (char c in password.ToCharArray()) secpassword.AppendChar(c);
ProjectContext pc = new ProjectContext(pwaPath);
pc.Credentials = new SharePointOnlineCredentials(username, secpassword);
//now you can query
pc.Load(pc.Projects);
pc.ExecuteQuery();
foreach(var p in pc.Projects)
{
Console.WriteLine(p.Name);
}
//Or Create a new project
ProjectCreationInformation newProj = new ProjectCreationInformation() {
Id = Guid.NewGuid(),
Name = "[your project name]",
Start = DateTime.Today.Date
};
PublishedProject newPublishedProj = pc.Projects.Add(newProj);
QueueJob qJob = pc.Projects.Update();
JobState jobState = pc.WaitForQueue(qJob,/*timeout for wait*/ 10);
}
}
I already answered this question in other question
How to authenticate to Project Online PSI services?

Resources