Xml DataType With Entity Framework

Requirement: Need to save an object collection in Sql Server Xml data type column.
Note: In Sql Server 2016 JSON support was added.

Steps:
1. Employee and Address classes declared.
2. Created EmployeeMapping of type EntityTypeConfiguration which is used by DbContext.
Note: Addresses collection should be ignored in mapping to avoid key required error on Address Entity.

Note: it’s not full proof code.

namespace EntityFrameworkXmlDemo
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Welcome");
bool retrieve = true;
var context = new SampleContext("connection string here");
if (retrieve)
{
var employee = context.Employees.FirstOrDefault(e => e.Id == 1);
var addresses = employee.Addresses;
}
else
{
var employee = new Employee()
{
Name = "Fanstastic"
};
employee.Addresses.Add(new Address()
{
Name = "Newyork",
Zip = 1234
});
employee.Addresses.Add(new Address()
{
Name = "California",
Zip = 7658
});
employee.SerializeAddress();
context.Employees.Add(employee);
context.SaveChanges();
}
Console.ReadKey();
}
}
public class SampleContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public SampleContext(string connectionString) : base(connectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new EmployeeMapping());
base.OnModelCreating(modelBuilder);
}
}
public class EmployeeMapping : EntityTypeConfiguration<Employee>
{
public EmployeeMapping()
{
this.ToTable("Employees");
this.HasKey(d => d.Id);
this.Property(d => d.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(d => d.Name);
this.Property(d => d.Address).HasColumnType("xml");
this.Ignore(d => d.Addresses);
}
}
public class Employee
{
private IList<Address> _addresses;
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public IList<Address> Addresses
{
get
{
_addresses = DeSerializeAddress();
return _addresses;
}
set => _addresses = value;
}
public void SerializeAddress()
{
var serializer = new XmlSerializer(typeof(List<Address>));
var stringWriter = new StringWriter();
serializer.Serialize(stringWriter, _addresses);
Address = stringWriter.ToString();
}
public IList<Address> DeSerializeAddress()
{
if (!string.IsNullOrEmpty(Address))
{
var serializer = new XmlSerializer(typeof(List<Address>));
var stringReader = new StringReader(Address);
return (IList<Address>)serializer.Deserialize(stringReader);
}
return _addresses;
}
public Employee()
{
_addresses = new List<Address>();
}
}
public class Address
{
public string Name { get; set; }
public int Zip { get; set; }
}
}
view raw Program.cs hosted with ❤ by GitHub

Code signing .Net assemblies with comodo certificate in Visual Studio

Requirements: Recently i got a requirement to publish code outside of our company as installation. We don’t want our users to see untrusted publisher error while using aour application.

Certificate from Comodo: You need to follow these steps to get (*.pfx) to sign the assemblies.

  1. Use only Internet explorer or Firefox . Chrome is not currently supported by Comodo.
  2. Create account and request for code signing certificate.
  3. After successful submission, you will receive email from comodo within 2 business days.
  4. Remeber, you need to use same system and same browser to install the certificate sent by Comodo.
  5. Once you install certifcate, you can export the certifcate as (*.pfx) file and sent the same to development team. Please secure this file with strong password.

As a developer: Follow these steps to sign the assemblies

  1. If you are getting error “Cannot find the certificate and private key for decryption.”. please follow steps to install your certificate. Follow Steps
  2. If you get error while signing “Cannot import the following key file: companyname.pfx. The key file may be password protected. To correct this, try to import the certificate again or manually install the certificate to the Strong Name CSP with the following key container name: VS_KEY_xxxxxxx”. now you can install key value pair to container by using below command."C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\sn.exe" i codesign.pfx VS_KEY_5FC66E4E834CAD9C
  3. In Visual Studio project properties, you can choose signing tab and then select the pfx to sign. i dont have luck with this approach, so i followed next step
  4. In Visual Studio project properties -> Build Events -> Post Build Scripts
    "C:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe" sign /f "C:\anyfolder\codesign.pfx" /p password /tr "http://timestamp.comodoca.com" "$(TargetDir)*.dll"
  5. Now all your project assemblies should be signed. you can open properties of an assembly to confirm whether digital signatures tab is visible.

Happy Coding!

Using Google Authentication in Windows Applications

Goal: We have windows application built using .Net and this application should be able to retrieve basic information about the user like name, email and his unique parameters like google id etc.

Google Libraries: Google has developed and maintaining libraries as nuget packages for Open Id authentication and services like Google Plus, Google Drive etc.

Note: you can search using “Google.Apis.{google service like plus, drive}”. I am currently using their “Google.Apis.Plus.v1” with version 1.14.0.550

Prerequisites:

  1. We need to create an application in Google developer console.
  2. Next create Project, Credentials (Client Id, Secret) and enable  necessary API permissions. I have enabled Google + Api

Note: For windows applications client secret is really not a secret, so we really no need to worry keep it in secret place.

Application Changes:

Step 1:

We have all the information need to authenticate our users by using GoogleWebAuthorizationBroker.

var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets() {ClientId = "your client id", ClientSecret = "your client secret" },
new[] {PlusService.Scope.PlusMe, PlusService.Scope.UserinfoProfile, PlusService.Scope.UserinfoEmail}, "me", CancellationToken.None);

Step 2:

After step 1, your application should open browser for user to authenticate and authorize your app to use requested scopes.  Now we use below code to create Person Resource.

Note: Since our app is designed to get currently logged in user, we need to query people resource with id as “me”.


// Create the service.
var service = new PlusService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Sample",
});
var peopleResource = service.People.Get("me");
var person = await peopleResource.ExecuteAsync();

Step 3:

Now person object has all the basic information like email, display name, profile url etc.

Happy Coding.