Backlup OneNote Files
OneNote is a great tool, which is not only free and available for all major platforms
(PC, Mac, Android, iOS, Windows Phone,..), but also very flexible and can store almost any kind of data and sync it to many clients, so that you have your data always available..
One of the features i really like and which is not very well known, is automatic OCR, when importing pictures, eg. using Office Lense
But here i wanted to show, how you can have your OneNote files automatically backed up using the Office 2010/2013/2016 Client:
Open File=> Options and define, where the default backup folder should be.
There you can also define, how many old copies should be stored in the backup folder
And the backup will be done automatically, but only for the files, which are currently open!
More infos here:
https://www.heise.de/select/ct/2017/15/1500314005139156
.NET 4.x Compatibility
.NET 4.5 was created as an in place upgrade.
This means, it will replace all the 4.0 binaries and therefore introduces not only new functionality, but also new behavior, which can break existing applications.
For this reason, there are many ways to upgrade the base functionality, but still make sure, that old 4.0/4.5/4.6) behavior in your application is retained.
Very important to not break existing 4.0 code is, that 4.5 and up will assume, that compatibility is needed. Upgrading a machine should therefore not create any issues…
Have a look at this very good posting to get a lot of important details:
https://blogs.msdn.microsoft.com/webdev/2012/11/19/all-about-httpruntime-targetframework/
Using Group Managed Service Accounts with IIS 10 on Server 2016
Using NetworkService powered application pools does have the nice effect, that there is no password needed, because the pool will be running with the credential of the webserver machine account, which is a domain account, where no password management is needed.
To access resources on the network, the webserver machine account must be enabled on the network destination and everything is fine and secure using windows authentication or Kerberos
This approach is good enough, if the scenario is limited to one application per server, because the minute you need another application, which does have different requirements in terms of security, then this approach will fail.
Lets assume, there are 2 web apps on the machine, which each does have its own SQL Server DB and which should not be allowed to access the other ones data.
This scenario can only be used with custom domain accounts, if windows authentication should be used.
Only with 2 different accounts and 2 application pools, the security on each database can be limited to the one matching application pool.
But then someone has to manage this domain passwords and make sure, that they are not expiring, but still changed from time to time. A tedious task and the passwords are probably distributed across the company, hopefully in a secure way and not inside XLS or Textfiles…
Another way with Server 2016 is to use Group Managed Service accounts.
This requires, that Active Directory scheme is on level 2012 R2, only then, the feature “Group Managed Service Accounts” can be used.
Setup a Group Managed Service Account
Login to DC:
Enable gMSA globally on Domain
— for Lab environments we use the switch –EffectiveTime, so that we don’t have to wait for 10 hours, which usually should make sure, that AD sync is ready.
Add-KdsRootKey –EffectiveTime ((get-date).addhours(-10));
This will usually be done from the Active Directory team in your environment
Open ServerManager => Tools => Active Directory Administrative Center
Add new global SecurityGroup named gMSAGroup
Go to AD Admin Center and search for the newly created group (gMSAGroup)
OR: Use Powershell and first install the Powershell AD-modules
Install-WindowsFeature -Name RSAT-AD-PowerShell
Then create the global security group using
NEW-ADGroup –name “gMSAGroup” –path “OU=XYZ,DC=mydomain,DC=com” -GroupCategory Security -groupscope Global
Right click the gMSAGroup entry and add all the memberserver, which should be able to use the Group Service Managed Account IIS1Svc
or use Powershell:
Add-ADGroupMember "gMSAGroup” -Members "Server1$", "Server2$"
After adding all the memberservers to the Group Managed Service Group, they must be rebooted!
Create first gMSA Account on the DC: (max 15 chars)
New-ADServiceAccount IIS1SvC -DNSHostName IIS1Svc.corp.litware.com -PrincipalsAllowedToRetrieveManagedPassword gMSAGroup
optionally use –path to define, whe the account should be placed into the domain structure, eg:
-Path "OU=OUXy,DC=mydomain,DC=com"
Check in AD Admin Center, that the account is visible
S
Switch to MemberServer (HSW2K12R2Web1)
Install on MemberServers: Remote Server Administration Tools via Server Manager to get Active Directory Module for Windows Powershell
OR with Powershell: Install-WindowsFeature -Name RSAT-AD-PowerShell
Open Powershell Admin Console and
Install-ADServiceAccount IIS1Svc
If error is “access denied”, make sure, that the memberserver was added to the allow list of the group service group and the server was rebooted afterwards!
Create new AppPool in InetMgr:
Use this GroupServiceManaged Account and append “$” to the name and leave password empty
Use this Account for a web application.
When this web application will access a resource on another computer, it will then use this GMSA
More infos:
Using Docker on Windows 10 or Server 2016
Docker support comes in two different flavors on Windows:
- Windows Container
- Hyper-V Container
Both flavors can use the same images, but Hyper-V Container deliver more isolation between the containers
Hyper-V Container need Hyper-V support and therefore are currently not usable in Azure, unless the coming feature of “nested virtualization” is broadly available
Both flavors differentiate in this environment requirement and in the added startup switch –isolation=hyperv, when starting an image using a cmdline like this:
docker run –d –name <myIISContainerName> –h <MyIISHostname> –p80:80 microsoft/iis –isolation=hyperv
More about the differences here:
https://docs.microsoft.com/en-us/virtualization/windowscontainers/quick-start/
Docker Installation
Installing Hyper-V Container on Windows 10:
https://docs.microsoft.com/en-us/virtualization/windowscontainers/quick-start/quick-start-windows-10
Install Docker (Windows Container) on Server 2016
Installing Container feature using ServerManager is not enough! The following Powershell scripts must be executed!
- Install-Module -Name DockerMsftProvider -Repository PSGallery –Force
- Install-Package -Name docker -ProviderName DockerMsftProvider
- Restart-Computer –Force
- SConfig ==> Option 5 to install Updates
Install Windows Server 2016 on Azure
Add a VM based on “Windows Server 2016 Datacenter – with Containers”
Docker is already included and also a few base images are there
Define terms like image and container
The term image is used for a prepared environment, which can be started multiple times.
Each instance on start will create a container, which runs with its own IP and completely sepearated as unique machine with its own machinename
Note: image names must be all lowercase!
Docker commands
List locally availble images:
docker images
List public available images from Microsoft:
https://hub.docker.com/u/microsoft/
Some of the images with a short description:
- https://hub.docker.com/r/microsoft/nanoserver/
Can run IIS and dotNetCore, but not Full .NET!
Small download size of about 800 MB - https://hub.docker.com/r/microsoft/windowsservercore/
can run all kind of roles, but without GUI support
Able to run IIS, SQL,…
Downloadsize about 8 GB - https://hub.docker.com/r/microsoft/iis/
Based on Windows Server Core including IIS
RUN powershell -Command Add-WindowsFeature Web-ServerTo use .NET Framework inside IIS, the following features must be added:
RUN powershell -Command Add-WindowsFeature NET-Framework-45-ASPNET
RUN powershell -Command Add-WindowsFeature Web-Asp-Net45
==> add to dockerfile, see scetion “Create new images using dockerfile”
- https://hub.docker.com/r/microsoft/aspnet/
Based on microsoft/iis includes ASP.NET in different versions
The following images contain full .NET Framwork, but NO IIS
- microsoft/dotnet-framework:3.5
- microsoft/dotnet-framework:4.6.2
- microsoft/dotnet-framework:4.7
Run a docker image interactive
docker run –it <nameOfImage> <cmdToExecute>
Example:
docker run –it microsoft/iis cmd
Run a docker image in the background
docker run –d –name <nameOfContainer> –h <HostName> –p<PostPort>:<ContainerPort> <nameOfImage>
Example:
docker run –d –name MyIIS1 –h MyIIS1 –p80:80 microsoft/iis
Run a docker image in the background using Hyper-V
docker run –d –name <nameOfContainer> –h <HostName> –p<PostPort>:<ContainerPort> –isolation=hyperv <nameOfImage>
All processes are listed in the hosts taskmanager with a job Task Id, which is unique for a container
Port handling
-p lets define a port, which will listen on the host and will be forwarded to the container
Local firewall and Azure Network Security group rules must be adjusted!
List local docker container with status
docker ps –a
Run a cmd inside a running container
docker exec –i <NameOfContainer> <CmdName>
Example:
docker exec –i MyIIS1 cmd
Check IP address of running container from Powershell
docker inspect –format ‘{{ .NetworkSettings.Networks.nat.IPAddress }}’ myIIS
More inspect commands:
https://docs.docker.com/engine/reference/commandline/inspect/#extended-description
Stop a running container
docker stop <nameOfContainer>
Example:
docker stop MyIIS1
Remove stopped container
docker rm <NameOfContainer>
Example:
docker rm MyIIS1
Remove local image
docker rmi <imagename>
Example:
docker rmi microsoft/iis
Create a new docker image from existing container
Make sure, that container ist stopped
docker commit <ContainerName> <newimagename>
Save a docker without docker repository
docker save –o c:\temp\myimage.tar <imagename>
Display image history
docker history <imagename>
Create your own Docker Registry
https://github.com/docker/docker.github.io/blob/master/registry/deploying.md
Create new images using dockerfile
New base image which includes ASP.NET 4.5 Framework and WebDeploy
Lets define a new image, which should be based on microsoft/iis and also run .NET and should be able to allow remote installation using WebDeploy.
The name of our new image should be webdeployimage (names must be all lowercase!)
To include WebDeploy functionalilty, we need to download the WebDeploy-MSI from here:
https://www.iis.net/downloads/microsoft/web-deploy
The resulting downloaded file is named WebDeploy_amd64_en-US.msi
Lets copy this file to c:\temp\WebDeployImage
Create a textfile named dockerfile in the same directory with content below
A dockerfile is a list of docker commands which will be executed on every startup of the container image.
FROM microsoft/iis
RUN powershell -Command Add-WindowsFeature NET-Framework-45-ASPNET
RUN powershell -Command Add-WindowsFeature Web-Asp-Net45
ADD WebDeploy_amd64_en-US.msi /temp/
RUN msiexec /i c:\temp\WebDeploy_amd64_en-US.msi /qn
Note, that destinationpath fo ADD cmd uses unix style / and not \
Now build the new image using this cmd, where the path points to the location, where the dockerfile is located
docker build -t webdeployimage C:\temp\WebDeployImage
after this a new image named webdeployimage should be listed using docker images
Another new image which is based on webdeployimage and includes MyDockerampleWebApp
Create a WebDeployPackage from any existing .NET app on your IIS using Export from Inet Manager. This will result in a zip file named MyDockerSampleWebApp.zip in this example.
Create a new directory c:\temp\MyDockerSampleWebApp and there create this dockerfile:
FROM webdeployimage
ADD MyDockerSampleWebApp.zip /
RUN Powershell -Command "Add-PSSnapin WDeploySnapin3.0; Restore-WDPackage -Package c:\MyDockerSampleWebApp.zip
Now build the new image using this cmd, where the path points to the location, where the dockerfile is located
docker build -t mydockersamplewebappimage C:\temp\MyDockerSampleWebApp
after this a new image named mydockersamplewebappimage should be listed using docker images
Now run a new container using this image
docker run –d –name sampleapp1 –h sampleapp1 –p80:80 mydockersamplewebappimage
Access your hostmachine now using the given port (in this example 80)
http://YourServername/MyDockerSampleWebApp
Note: You have to make sure, that the host port is available and not used from another instance or local IIS
Add Remote Management to a Docker image based on microsoft/iis
docker run -d –name iis1 -h iis1 -v c:/shared:c:/shared microsoft/iis
docker exec -i iis1 powershell
Install-WindowsFeature -name Web-Server -IncludeManagementTools
Dism /online /enable-feature /featurename:IIS-ManagementService /all
– Enable remote access
New-ItemProperty -Path HKLM:\software\microsoft\WebManagement\Server -Name EnableRemoteManagement -Value 1 -Force
net user AdminUser P@ssw0rd1 /ADD
net localgroup administrators AdminUser /add
net start wmsvc
ipconfig
Ipconfig will return the IP of the docker container.
Now switch back to the Docker host or any other machine in the network, which does have the IIS Management Console installed and connect to this docker image using the IP address and username/password defined above.
Backup running Windows 10 installation using c’t WImage
Backup a running Windows installation to retrieve or reset it later
Backup up my current windows installation is a good way for me, to make sure, that i can continue working after a hardware failure asap.
Otherwise i’d have to start with manual installation of the Windows 10 base OS, then Office, all my tools and then the development environment, which in my case is mainly Visual Studio 2017.
Doing this manually and starting with the Windows 10 base OS usually takes 2 or more days until the environment is in a similiar state, as it was before the crash.
I’ve had this bad events happen several times in the last few years and most of the time a harddisk / SSD defect was the reason.
Although all my data was protected by an hourly update to the Azure cloud using Cloudberry Desktop Backup, my Windows installation and all the settings were not.
My previous solutions: Acronis True Image and DriveSnapshot
My first approach some years ago was to use image based backup software, like Acronis TrueImage and DriveSnapshot
Acronis does have much more features, but i came back to the very simple and small DriveSnapshot solution, which doesn’t need any installation.
Just download and run a small 400kb Exe-File to start backup or restore.
For private users, it’s even free.
DriveSnapshot creates images based on complete partitions and the images can be mounted to access individual files using the same Exe.
Its able to save a running Windows installation using either builtin or its own snapshot mechanism.
To restore data, you can either mount the image on another machine or boot from a Windows installation USB stick, then press F10 in the first dialog to come to a cmd-line and then start the DriveImage exe, which you have to copy before to the USB stick.
Some month ago i wanted to move my running Windows installation from a Lenovo W530 to a Microsoft Surface Book, which i wasn’t able to do using Drivesnapshot.
The reason is, that the Lenovo installation was done using Bios-Mode, while Surface Book only operates in UEFI mode.
This was the time, when i remembered the article about c’t WImage.
The german computer magazine c’t is one of the oldest IT magazines in germany.
The name ct comes from “Computer & Technology” and they are still the #1 in the german computer magazine market for IT professionals and programmers.
So all the honor for the following description goes to Axel Vahldiek and his colleagues in the heise medien team. They provide the article and some more infos on this topic here in german language: http://ct.de/y6ev
I only used all their information to compress them into a single list to that i’m able to repeat them, when i need it.
Using c’t WImage Qucklist:
Use c’t WImage with USB Stick to save current Windows installation as Image, which can be restored using the regular Windows Setup program
More infos: http://ct.de/y6ev
Note:
My description is based on the current Windows Version, named
Windows 10 Creators Update (1703), which includes a few things, which are relevant for the list below. Altough, the ct WImage solution was already available for previous Windows versions, i’d recommend to use 1703 or later.
The main feature was the corrected handling of multiple partitions on USB-sticks.
Previous versions were not able to display more than the first partition on a USB stick and the solution was therefore not usable with a USB stick, but only with a USB harddrive.
Now here is the list of things you have to do for creating a backup for your curently running Windows 10 Installation:
- Download Media Creation Tool from:
https://www.microsoft.com/de-de/software-download/windows10 - Run Tool and select “Download media for other computer”
- Select Windows Version & Architecture (in my case Windows 10, X64)
- Then select “Download as ISO” and save .ISO file to disk ….
- Skip the step “burn to DVD”…, just click “Finish”
- Start “Create a recovery drive”
- Unselect “Back up system files…”
- Select the USB drive, where the boot files should be copied to
- Understand the warning, that the USB drive will be DELETED,
then click “Create” - If Explorer dialog comes up and asks for “formatting..” Select “NO”!!!
- The recovery drive is ready
- The USB drive should now have 2 partitions on it.
The first should be 32 GB in size, which is to big, so we will shrink it!– Because Windows is unable to shrink it, we need to:
A) Copy the files to a temp dir (300 MB) (exclude System volume information)
B) Delete the volumeC) Create a new volume with size=1000 MB of type=FAT32
Name it “USB-Boot” and after formatting using FAT32, make sure to activate the partition!
- Copy the temporarily saved files back to this new partition
- Create another volume using all remaining space, format it with type=NTFS and name it “USB-DATA”
- Double click the previously downloaded Windows Installation-ISO and it will be mounted as a new drive letter
- Select all files and copy them to the root dir of the “USB-DATA” partition
- Open the directory sources on the USB-data parttion and
delete the file “install.wim” or “Install.esd”,
Note, that only one of them will be there! - Unzip all files from the Zip-Archiv “ctwimage64.zip” into the root of the USB-Data partition
Prepare the backup process on the USB-drive with the ct files
- Open Admin-cmd and cd to USB-Data partition drive letter
- run ctwimage2-bootmaker64.bat from there
- The script will now ask, for correctness of USB-Boot and USB-data drive letters
- Type “Y” and it will finish with “Fertig”
Check whether your machine does boot from this USB media
- Now reboot and check, whether its possible to boot from the USB drive.
Windows Setup should come up and then complain, that there are no Windows Installation media files, which is correct. (We deleted Install.WIM / or .ESD)
- Reboot back to Windows to start the Backup
Start the backup process
- Run “ctwimage2-64.bat” from Admin Cmd from USB-Data partition
- Wait until 100% success message appears.
Note, that this can take a few hours, be patient!
Possible problems & solutions to it
Problems which occurred in my case:
This might be, because i’m using a managed Enterprise edition installation, which was customized from our internal IT.
The problem was, that running the script ctwimage2-bootmaker64.bat returned this error messages in red:
set operation=*** Windows RE auf Windows-Partition verschieben ***
reagentc /disable >nul 2>nul
FAILED: Error message: already disabled…
- Commented out this statetement, then started again…
- Now the Backup process run to 100%,
but at the end failed again with this messages, which i ignored, because of the same reason in the step before
Testing the backup on another machine or even better on the same machine is highly recommended as you should do with every backup solution.
Only then you can savely assume, that the restore will work, when you really need it.
And of course you should do the Backup steps from time to time, so that you are able to restore a kind of current installation and not have to apply a lot of updates after your restore.
I create a new backup after each domain password update, otherwise you’ll get into the “trusted relationship” problem, where your domain controller does not accept your machine, if it’s to old…..
But that applies only, if your installation is domain joined, which i plan to stop using in the near future….. but that’s stuff for an
A nice detail about multiple backups of the same or other machines on this USB-device is, that it will use the WIM-based feature of deduplicating files based on thewir hash.
This means, that it will not store the same file twise or more, but only increase a reference count.
This will keep the amount of space needed for multiple backups of one or many machines down to a minimum.
During restore, you can use the machine name and the date/time stamp to select a backup for restore…
other blogpost….
Comments are very welcome!,
ITTT-triggered: Daaaaaanke für all eure Glückwünsche!
via Facebook
Open Live Writer arrived as app in the Windows 10 store
ITTT-triggered: Holoportation using HoloLense is… cooool http://ift.tt/1XSKPoo
via Facebook
Create Windows 8.1 Store app from blank template using simple MVVM pattern
Create new project in VS 2013 using “Blank App” template
Make the ViewModel bindable
Add a new directory ViewModels and add a new class BaseViewModel.cs insde this directory with this content inside the namespace:
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
}
Add another class file called MainViewModel.cs with this content inside the namespace:
public class MainViewModel : BaseViewModel
{
private string firstname = String.Empty;
public string Firstname
{
get { return firstname; }
set { SetField( ref firstname, value ); }
}
private string lastname = String.Empty;
public string Lastname
{
get { return lastname; }
set { SetField(ref lastname, value); }
}
}
This way the properties in MainViewModel will automatically be able to databind in both directions.
Create a singleton for central access to the ViewModel
Now we must find a way to access the ViewModel from every place inside the app.
This can be done using a singleton pattern like this in app.xaml.cs:
private static MainViewModel myMainViewModel = null;
public static MainViewModel MyMainViewModel
{
get
{
if (myMainViewModel == null)
{
myMainViewModel = new MainViewModel();
}
return myMainViewModel;
}
}
Define the UI
Now add a few controls to Mainpage.xaml.cs (red block)
Setting the DataContext
in Mainpage.xaml.cs inside the ctor:
Please note:
Setting the DataContext in the XAML-file using <Page.Resources> does create a new instance of our MainViewModel class each time we open the MainPage, which is not what we want.
Therefore this statement for setting the DataContext is NOT USED here!
See the section “Adding designtime support..” below!
<!-- Does create a new instance every thime, because it's not using our singleton -->
<!--<Page.Resources>
<ViewModels:MainViewModel /> NOT USED HERE !!
</Page.Resources>-->
Saving data when the OS terminates / suspends the app
Now add saving and loading to LocalSettings or RoamingSettings using code like this in the OnSuspend event:
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
ApplicationData.Current.LocalSettings.Values[Constants.LocalStorage.VIEWMODELDATA]
= Utility.SerializeToString(App.ViewModel);
deferral.Complete();
}
Helper class for serialization / Deserialization
public static string SerializeToString(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
public static T DeserializeFromString<T>(string xml)
{
XmlSerializer deserializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xml))
{
return (T)deserializer.Deserialize(reader);
}
}
Reload data after app was suspended
Then make sure, that when the program starts up after it was supended through the OS, that it’s loading the last data using code like this in the OnLaunched event:
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
if (ApplicationData.Current.LocalSettings.Values[Constants.LocalStorage.VIEWMODELDATA] != null)
{
var serializedData
= ApplicationData.Current.LocalSettings.Values[Constants.LocalStorage.VIEWMODELDATA] as string;
App.ViewModel = Utility.DeserializeFromString<MainViewModel>(serializedData);
}
}
Adding designtime support / Intellisense for binding statements
using Blend:
Open MainPage.xaml in Blend and click on “Set design-time DataContext” in the right lower corner:
Select DesignInstance in the following dialog like this:
Create demo data for design time
Create dummy data in the ctor of the ViewModel and decide whether its running in design mode using:
if
(Windows.ApplicationModel.DesignMode.DesignModeEnabled)
.
Intro to ASP.NET WebAPI
WebAPI as part of MVC 4 projects template in VS 2012 allows to easily create REST based services. This services use HTTP verbs GET, POST, PUT and DELET for communicating with the server.
This way they can be very easily called from any client in any technology and due to the REST type interface will minimize the number of bytes transmitted.
In addition to this, the server will detect the format of the data, which should be delivered to the client. By default it will be a JSON stream, but its just a mtter of a different header type in the request to change the output to XML.
WebAPI uses a lot of "Convention over Configuration", whichmeans that many default settings are based on naming defaults. Of course all this can be changed, but it’s much easier and better to understand for other people, when following the default conventions.
To create a new WebAPI project, use the MVC 4 template in VS 2012 and the select WebAPI in the following dialog
The project will then already have some setup code like route definition, which is defined in global.asax:
<pre>public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
} </pre>
which will call this function and make sure, that the route pattern /api/{controller} is handled
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Securing WebAPI using Basic Authentication
Securing any ApiController can be done by adding the [Authorize] attribute from System.Web.Http
To use Basic Authentication the following steps are needed:
Create a new class BasicAuthenticationAttribute:
public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response =
new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
else
{
string authToken = actionContext.Request.Headers.Authorization.Parameter;
string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
string username = decodedToken.Substring(0, decodedToken.IndexOf(":"));
string password = decodedToken.Substring(decodedToken.IndexOf(":") + 1);
if (username == password)
{
User user = new User() { UserName = username };
HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(user), new string[] { });
base.OnActionExecuting(actionContext);
}
else
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
}
}
}
The code above references this ApiIdentity class:
public class ApiIdentity : IIdentity
{
public User User { get; private set; }
public ApiIdentity(User user)
{
if (user == null)
throw new ArgumentNullException("user");
this.User = user;
}
public string Name
{
get { return this.User.UserName; }
}
public string AuthenticationType
{
get { return "Basic"; }
}
public bool IsAuthenticated
{
get { return true; }
}
}
Add the attribute [BasicAuthentication] to the ApiController
Now all calls must provide username and passwort in Basic Auth scheme format.
Example using WebClient:
private void btnGetData_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
string username = txtUsername.Text;
string password = txtPassword.Text;
wc.Headers.Add("Authorization", "Basic " +
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password))));
string jsonData = String.Empty;
try
{
jsonData = wc.DownloadString("http://localhost:43153/api/values");
}
catch (Exception ex)
{
jsonData = "Exception: " + ex.Message;
}
txtJSONData.Text = jsonData;
}
.