Showing posts with label web. Show all posts
Showing posts with label web. Show all posts

Thursday, December 29, 2016

Assigning Certificates to applications (without IIS)

Hi,

it is hard work to implement a web page using HttpListener! It is easy to turn the HttpListener to listen to https (by changing the listening prefix) but to get this up and running is still a challenge!

You need to:


I followed the instructions of http://sunshaking.blogspot.co.at/2012/11/https-communication-httplistener-based.html , but still needed more than 4 hours to get it up and running. Important is to work with the generated pfx file! It is clear but it is not mentioned explicitly in the article... also keep an eye on the icons. if you have the pfx file, you need to see a lock symbol in the mmc.

kr,
Daniel

Thursday, December 22, 2016

C# WCF WebOperationContext - best practice in error handling

Hi,

WebOperationContext is typically used in a WCF REST method so that method can access the incoming request and outgoing response.

(see: http://stackoverflow.com/questions/18747581/difference-between-weboperationcontext-current-and-httpcontext-current )


... in my projects I wrap OperationContract-ed methods with error handling. You can imagine that with a standard method like MessageWrapper which uses an Action or Function and implements the code in lambda-style in-line. The MessageWrapper handles the Exception handling and sets the Response ErrorCode (WebOperationContext.Current.OutgoingResponse.StatusCode) to 200 if everything is fine or to error if an exception occurred.

public T MessageWrapper(Func<T> action) where T : class{
  try 
    SetStatusOK(); 
    return action(); 
  } catch (Exception exc){
    SetStatusError(exc);
    return null;
}

public ReturnObject Operation() {
  MessageWrapper(()=> return new ReturnObject("some", "parameters"));
}

... here I would love to mention, that with Castle you can create interceptors where you don't have to put the MessageWrapper inside the business logic code. You can keep this as an aspect (AOP) which can be configured at startup.

And here one more thing that helped a lot me during development time. You can set additionally to the StatusCode also a StatusDescription which e.g.: is displayed in your browser of choice as an explanation for an error. So StatusDescription = exc.Message is simply gold!

kr,
Daniel

Thursday, December 8, 2016

REST APIs

found 2 very nice projects which are used to develop REST APIs. They are designed high level and can be used for code generation and documentation.


  • http://swagger.io/
  • http://raml.org/

with the ability to move swagger to raml using the project swagger to raml ( http://raml.org/projects/projects#q:swagger2raml ).

Important for me: both work with Java and .NET ... Swagger even has Client Generation for Angular (1 and 2).

Currently not available: .NET WebApi which would be great.

kr,
Daniel

Wednesday, August 3, 2016

Dates in WCF - JavaScript communication over JSON

Hi,

today we had really big troubles with WCF and javascript communication. We wanted to send dates over the wire and use its value for additional libraries (which rely on type Date). After hours of playing around I finally solved it with JSON.parse.

Different approaches starting from overriding the WCF object serializer till writing a custom json parser libraries had been tried but finally all these are very unstable.

Resources I found to solve the problem
- Hanselman ... describing my problem
Stackoverflow ... similar issue (solution mentioned)
- Documentation ... after knowing the solution a perfect page :-)

JavaScript/HTML testproject follows...

kind regards,
Daniel




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<html><head></head><body>

<script>
function test() {

var objectString = '{"name" : "Daniel", "date" : "\/Date(1293034567877)\/"}';

//___________________________________________________________________________________
//

var objectDataWithParse =  JSON.parse(objectString);

var objectDataWithDate = {
    "name": objectDataWithParse.name,
    "date": new Date(parseInt(objectDataWithParse.date.substr(6, objectDataWithParse.date.length-8)))
};

function parseReviver(key, value) {
    var a;
    if (typeof value === 'string') {
        if(value.substr(0, 6) == '\/Date(') {

            alert(value.substr(6, value.length-8));
            return new Date(parseInt(value.substr(6, value.length-8)))
        }
    }
    return value;
};

var objectDataWithReviver = JSON.parse(objectString, parseReviver);

//___________________________________________________________________________________
//

var outObj = {};
outObj = objectDataWithDate;
outObj = objectDataWithParse;
outObj = objectDataWithReviver;

//___________________________________________________________________________________
//

document.getElementById('outputDIV_json').innerHTML = objectString;
document.getElementById('outputDIV_name').innerHTML = outObj.name;
document.getElementById('outputDIV_date').innerHTML = outObj.date;

};
</script>

<div>
<button onclick="test()" >test</button>
</div>
<hr />
<div id="outputDIV_json" ></div>
<div id="outputDIV_name" style="float:left;margin-right: 5px;margin-top: 5px; background: lightgreen"></div>
<div id="outputDIV_date" style="float:left;margin-right: 0px;margin-top: 5px; background: orange"></div>

</body></html>

Sunday, June 26, 2016

Castle and WCF (3)

Hi,

I went through hell to get this stuff work, but finally I got it. As partly mentioned in part 2 of this series I wanted to create an IIS hosted rest-service without the need of adding a svc-file. So I created an empty web-project, added a global.asax file and added the following code in the Application_Start method:


WindsorContainer
 container = new WindsorContainer();


ServiceHostFactoryBase factory = new WindsorServiceHostFactory<RestServiceModel>(container.Kernel);
container.AddFacility<WcfFacility>(f => f.CloseTimeout = TimeSpan.Zero)
  .Register(Component.For<IMyService>()
                     .ImplementedBy<MyService>()
                     .LifeStyle.Is(Castle.Core.LifestyleType.Singleton));

RouteTable.Routes.Add(new ServiceRoute("MyService", factory, typeof(IMyService)));

There is no need to configure the service in the web.config-file except ASP.NET Compatibility which is needed by the Routes.Add code-line.

kind regards,
Daniel

Friday, June 17, 2016

Castle and WCF (2)

Hi,

first of all I got the feedback that "Castle" is the wrong naming... so for clarification: with Castle the whole technology-stack of http://www.castleproject.org/ is meant including (especially) DynamicProxy and Windsor.

Further research brought me to the follow up question whether it is possible to implement a service with a non-empty (standard) constructor. Yes, this is also possible ( stackoverflow.com ). You simply need to:

  • create a Custom-ServiceHostFactory (base class: ServiceHostFactory) and 
  • override CreateServiceHost which should create a Custom-ServiceHost. 
  • Each implemented service contract (loop over this.ImplementedContracts.Values) should get a Custom-Behavior (interfaces: IContractBehavior and IInstanceProvider) added. 
  • In the instance provider happens the magic of creating a service with new (override the two GetInstance-methods). 
A step-by-step guide can be found on MSDN here. Here a quote of the github answer referenced above:
You can easily generalize this approach, and in fact some DI Containers have already done this for you (cue: Windsor's WCF Facility).
 A tutorial how to use the WCF facility can be found here and here. A walk-through "DI in WCF in 5min" can be found here (this article shows perfectly that DefaultServiceHostFactory enables you to create services with the full power of DI).

I am looking forward to test that approach with "RouteTable.Routes.Add(new ServiceRoute(...))".

kr, d

Thursday, June 16, 2016

Castle and WCF

Hi,

it is a quite hard task to build a good and stable back-end. The request/response interfaces therefore are often full of boiler plate code. In my .NET applications I rely on WCF and REST services. First questions:


Can I create services on the fly or do I have to create a *.svc-file as described in 90% of the tutorials?

Answer: Yes... with ServiceHostFactory ( http://stevemichelotti.com/restful-wcf-services-with-no-svc-file-and-no-config/ )


Can I/Do I have to still use IIS?

Answer: Both is possible


Do I need to be a web.config expert?

Answer: You can config your stuff in code too.



So summarized: I can create ServiceHostFactories on the fly and can use Castle to inject the dependencies... great. Castle provides even more: WCF Integration Facilities... https://github.com/castleproject/Windsor/blob/master/docs/wcf-facility.md

There seemed to be an active community on writing facility based, config less, castle-driven backends like at https://github.com/vcaraulean/WcfWithoutConfigFile/blob/master/WcfWithoutConfigFile.WebHost.Castle/Global.asax.cs

... really cool... I am looking forward to use that stuff and post some first results...

kind regards,
Daniel

Friday, May 13, 2016

Webserver cassini

I didn't know that the logic of the IIS is part of .net's fcl... Here a project using this: cassini

See: https://msdn.microsoft.com/de-de/library/bb979483.aspx

King regards,
Daniel

Thursday, November 26, 2015

Book-Review: Responsive Web Design with AngularJS (Sandeep Kumar Patel)

The book is a low level beginner’s guide to AngularJS and some of its responsive capabilities if you are using AngularJS pure (without twitter - bootstrap). A responsive portfolio-application is built as a show-case to introduce the reader to common problems of the field. Other technologies like SASS and JSON are mentioned and partly shown. The book ends with tool advises like the Chrome-F12-tools and Batarang.
AngularJS topics:
-          Templates and DataBinding (MVW)
-          Partials
-          Router
-          Modules / Controller / Scopes
-          Directives (built-in and custom)
-          Custom Services
-          Events / $Watch
-          Publish-Subscribe with $emit, $broadcast - $on
It was easy to read and with good background information, but I would say that after reading it you are not 100% able to build an AngularJS application responsively (and even not responsively) your own. Further investigations are definitely necessary...

kind regards,
Daniel

Thursday, October 29, 2015

bootstrap editors

Hi,

after a small break I am back reincarnated as a web developer.

Today I played around with bootstrap trying to change the style of my web-page.

Following resources helped me much
- http://getbootstrap.com/
http://www.bootply.com/
- http://fortawesome.github.io/Font-Awesome/
http://glyphicons.com/

but it didn't feel right to work online (and to collaborate without possibly wanting it).

I found other resources to consider
http://www.layoutit.com/
http://brix.io/

... again web, but there are still the stand-alone, cloud-less, good-old tools like:

commercial desktop products:
http://pinegrow.com/

free desktop products:
http://pingendo.com/


What I did not found are true alternatives to bootstrap itself and in fact I don't even need any. Bootstrap is a really good designed, good working framework which does create good looking pages.

kind regards,
Daniel

Tuesday, December 16, 2014

ASP.NET developer efficiency

... because I was asked how to develop asp.net faster... here my top 10 shortcuts which boosted my work (in vs-studio 2013 using the standard key mapping for c# developers)

  1. press ctrl + "," to move between files
  2. press f12 to go to definition
  3. press ctrl k+r for find all references
  4. press f8 to move in the list of found items
  5. press ctrl+shift+b to compile
  6. press ctrl + "-" to jump back in history (regarding cursor position)
  7. press ctrl + alt + p to attach to process (w3wp for iis hosted asp.net) and type the name of the process
  8. press ctrl + shift + f to find stuff / h to replace
  9. press ctrl + "." to add references, implement interfaces and stuff
  10. press alt+tab to jump to browser, f5 for refresh (sorry for mentioning that :-) ).

cheers, Daniel

Wednesday, May 28, 2014

find colors for a style sheet

Hi,

today I needed some colors to build a website (or in detail to build a css style sheet).

The following pages supported me much while choosing matching colors:

- https://kuler.adobe.com
- http://colorschemedesigner.com/

Kind regards,
Daniel

Tuesday, April 22, 2014

Creating a web page using JavaScript

Hi,

today I was working with javascript. I was trying to reuse my knowledge of .NET and OOP to build a webpage, but it didn't really worked:

  • Classes are functions (I think). 
  • IntelliSense in Visual Studio is bad. 
  • Using a loosely typed language makes it easy to fail.

... but never mind... let's see what I learned today. At first I realized that a function seems to be a good way to stick to OOP in javascript.

//-----------------------------------------------------------------------------
// class Credential
//-----------------------------------------------------------------------------
function Credential(userName, password) {
    // Username
    this.UserName = userName;
    // Password encrypted
    this.Password = password;
}

... as a C# developer my eyes were bleeding while I was staring at these lines of code (no data types and only these "functions"), but anyway, what we got is something like a class we can use with public members. Creating a "var x = new Credential('admin', 'password');" instantiates the class.

In the next step I created a Controller class for my webpage like this:

function PageController() {
 
}

and it simply seems to work as a class with no functionality. My next challenge was to add static members to this class, because I wanted to use this class as a static class only. I was surprised to add a variable outside of the function block, but with the following line it seem to work:

// stores username and password
PageController.CurrentCredentials = null;

and moreover I was even able to add non-static members from outside the function using PageController.prototype.XY... again something strange for the good old c# guy... So I added a function in the same way as I did with the member variable:

PageController.Main = function () {

}

This function was intended to build me the link between javascript and html (in the following my html-file):

<!DOCTYPE html>
<html>
    <head>
        <title>ITADOS</title>
        <link rel="stylesheet" type="text/css" href="main.css" />
<script type="text/javascript" src="PageController.js"></script>
    </head>
    <body onload="PageController.Main();">
    <div id="PageControllerPlaceHolder"></div>
    </body>
</html>

... as we can see here the control of the page will be handed over to the PageController in the onLoad method. I think it is the most proper way to call onLoad, because the whole page is already received and rendered when onLoad is called.

I extended the main method with some code to get the magic in there...

//-----------------------------------------------------------------------------
// static function Main
// This function is the entry point called by the html part.
//-----------------------------------------------------------------------------
PageController.Main = function () {

   var content = "";

   if(PageController.CurrentCredentials == null) {
      content =    "<h1>Login</h1>\n"+
                   "<div class='LoginBox'>\n" +
                   "<div>Username: <input type='text' id='username' /></div>\n" +
                   "<div>Password: <input type='password' id='password' /> <input type='button' value='Login' " +
                                         "onclick='PageController.Login();'/></div>\n" +
                   "</div>\n" ;       
    } else {
       content = "<img src='img.png'/>";
    }
    document.getElementById("PageControllerPlaceHolder").innerHTML = content;
}

what i did is:
  • check if we are already logged in
  • if so
    • show an image as success message
  • if not
    • show a login box and add all the code necessary to proceed
  • place the content to the html-div tag

Now for completness only I add this last function to the blog entry, but it is only a dummy test method:

//-----------------------------------------------------------------------------
// static function Login
// This function will be called when the credentials are submitted. It creates
// a user context and reinitializes the dashboard.
//-----------------------------------------------------------------------------
PageController.Login = function () {
    // TODO: make the credential check by calling a remote service...
    PageController.CurrentCredentials = new Credentials();
    PageController.Main();
}

... so what we still haven't seen is the css file of the page:

body {
background-color: orange;
}

h1 {
margin-top:50px;
text-align: center;
}

div.LoginBox {
position:absolute;
left:50%;
width:300px;
padding:3px;
margin-left:-150px;
background-color:rgba(255,255,255,0.3)
}

... now the whole code is posted in the blog entry and we can summarize:



First thing to mention is that object oriented programming is absolutly possible in javascript. I saw a lot of possiblities e.g.: inheritance (by using: SpecialCredentials.prototype = new Credentials(); ), static vars and functions, public variables (using: this.VarName=value;), private variables (using var VarName = value;) and the same with private and public functions; and constructors. What I haven't found is: interfaces, abstract classes and protected methods, but there most be a reason why they built typescript (typescriptlang.org quote: TypeScript offers classes, modules, and interfaces to help you build robust components.) and maybe http://coffeescript.org/ should be mentioned here too as an other example of javascript derivates.

It is easy to start with javascript (using a lot of google-support) and easy to see results. What is absolutly awesome is this php approach using innerHTML and placeholder instead of php's if this-that echo "some-stuff". Every php-programmer will easily be able to build such a webapplicaion as seen above using the way to work he is used to. The cool thing here is that you have the code executed locally and so it is fast as hell without any need of reloading a whole page. A disadvantage is that you have no browser history (in such an approach) what I missed very hard while debugging the login page.

What was absolutly surprising to me was the fact that my chrome web tools provided a perfect debugging-IDE where I can see javascript errors, can set breakpoints, see variables and their state and values... After some research I found out that the guy, who developed firebug, moved to google to build these chrome toolsets. So there was no way for this tool not become awesome.

What I want to point out at last is the proper separation between html, javascript and css. In my example the html file is an empty page which says: I want this way to look (using a css file) and this kind of business logic (using a javascript file) and in the second step it simply hands over the control calling a javascript function (like Main in my example). The css here is a list of style information which will/can be used. The javascript code contains the actual business logic and enables the page to be dynamic and useful. The problem here is that you can't build a service in pure javascript because you need server-side code to e.g.: get data. My next project in javascript will be to find out how to get data from a server in an easy way using (I think) websockets...

Kind Regards,
Daniel