Search This Blog

Thursday, 1 August 2024

CoreWCF - Service and client creation step by step

 CoreWcf is used with .Net Core versions. Let us see how a simple WCF service and its client can be created using BasicHttpBinding

Creating the Server Side Setup - Core WCF Service Application

Step 1: Create a new core Wcf application 

> dotnet new web -n CoreWcfServer

> cd CoreWcfServer

At this point a basic boiler-plate code with a service contract and data contract is generated in the project as shown in the screenshots

Data Contract

Service Contract


Step 2: Make sure the following packages are installed. If not install them using the given command.

> dotnet add package CoreWCF.Http

> dotnet add package CoreWCF.Primitives


Step 3: In Program.cs make sure you add the highlighted lines in the screenshot. 

            Make a note of the Binding used at line: 12 - BasicHttpBinding(BasicHttpSecurityMode.Transport)


Step 4: Run the service project. Browse to: https://localhost:7104/MetaData 

This completes the configuration for a Core Wcf Service Application project


Creating a Console Client

The bindings exposed by the core WCF app can only be used by the client application. In this case, BasicHttpBinding can be the only binding that can be used

Step 1: Create a console app

> dotnet new console -n WcfConsoleClient

> cd WcfConsoleClient

Step 2: Make sure the same nuget packages are installed for this project, as installed for the WCF app.

             The server and client apps should contain the same ServiceModel packages

> dotnet add package System.ServiceModel.Primitives

> dotnet add package System.ServiceModel.Http

Step 3: Auto-generate the service reference to the Wcf Service app. For this we will require to install the tool dotnet-svcutil. This will help generate the service reference (proxy class), the metadata using which the calls to the service can be made

> dotnet tool install --global dotnet-svcutil

> dotnet-svcutil https://localhost:7104/MetaData?wsdl

** Some antiviruses can block the bootstrapperutil module in dotnet-svcutil, as it is not a signed module. Hence, use the following option

> dotnet-svcutil https://localhost:7104/MetaData?wsdl --noTypeReuse

 

Step 4: Add the following code in Program.cs



  

using ServiceReference;

using System.ServiceModel;


var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);

var endpoint = new EndpointAddress("https://localhost:7104/Service.svc");


var channelFactory = new ChannelFactory<IService>(binding, endpoint);

var client = channelFactory.CreateChannel();


CompositeType result = await client.GetDataUsingDataContractAsync(new CompositeType() { BoolValue=true, StringValue="A new string"});

Console.WriteLine($"Result from service: {result.StringValue} - {result.BoolValue}");


((IClientChannel)client).Close();

channelFactory.Close();

Console.ReadKey(); 


Step 5: Run your Wcf Service App first, then run the WcfConsoleClient

 

Wednesday, 10 January 2024

Quick Tech Tips - Attaching a Logger middleware to Redux

 To add a logger middleware to the redux application, the following steps can be followed

1. Install 'redux-logger' locally for your project


2. The file where redux store is created in your application, make the changes as follows (marked yellow)

import {configureStore, combineReducers} from '@reduxjs/toolkit'
import { purchaseReducer } from '../Reducers/Reducer';
import logger from 'redux-logger';

const rootreducer = combineReducers({purchaseReducer});
export const shop = configureStore({
                                    reducer:rootreducer,  
                                    middleware:(getDefaultMiddleware) => getDefaultMiddleware().concat(logger)}
                                 );

3. That's it. Each time you alter a state, The output should look as follows



Quick Tech Bits - React Redux Integration Using Hooks

 Steps to create and integrate Redux Application with React using @reduxjs/toolkit and Hooks

1. To create a redux aware react app, the following installations are required.

2. Create the actions, reducers, store as follows   

Actions > Action.js

 
export const BUY_ICE = 'BUY_ICE';
export const BUY_CHOC = 'BUY_CHOCOLATE'
 
//Create actions
export const buyicecream = () => {
    return {
        type: BUY_ICE
    }
}
 


Reducers > Reducer.js

import { BUY_ICE, buyicecream } from "../Actions/Actions";

const initialState = {
    ice_stock: 100
}

export const purchaseReducer = (prevState = initialState, action) => {
    switch(action.type){
        case BUY_ICE:
           return {
                    ...prevState,
                    ice_stock: prevState.ice_stock-1
                 };
        default:
            return prevState;
    }

}


Store.js

import {createStorefrom 'redux'
import {configureStore, combineReducers} from '@reduxjs/toolkit'
import { purchaseReducer } from '../Reducers/Reducer';
 
const rootreducer = combineReducers({purchaseReducer});
export const shop = configureStore({reducer:rootreducer});
//export const shop = createStore(reducer); //Deprecated...
 


3. Create a react component. In this component import the new hooks "useDispatch", "useSelector". These hooks come from the library 'react-redux'. They perform the task of mapping the redux library's dispatch function to react component, mapping redux store object to react component respectively, as shown in the code below.

In this react component, a button that updates the icecream stock of the redux's store (as created above) is done.

import {useDispatch, useSelector} from 'react-redux';
import { buyicecream } from './Actions/Actions';

export let MyShop = ()=>{

    const dispatchfn = useDispatch();   //redux built-in dispatch fn to dispatch action to redux store thru reducer
    const shopData = useSelector(store => store.purchaseReducer);   //assign redux global store (state obj) to variable
    console.log(shopData);

    return(<>
        <div className='text-primary'>
            Ice cream Stock: {shopData.ice_stock}
        </div>
        <button className='btn btn-primary' onClick= {()=>dispatchfn(buyicecream())}>BUY ICECREAM</button>

    </>);
}


4. Add this to the index js or the route configuration in your react app. This component will be wrapped inside the <Provider> which is provided by 'react-redux' package.

import {shop} from './Store/store' //comes from redux's store created above
import {Provider} from 'react-redux';
import { MyShop } from './ReduxIntegration'; //react component

let ReduxComponent = () =>{
    return (
        <Provider store={shop}>
            <MyShop/>
        </Provider>
    )
}

//In the route configuration add it as follows
export let Container = () => {
    return(
        <BrowserRouter>
            <Routes>                           
                <Route path='/redux' element={<ReduxComponent/>}/>
            </Routes>
        </BrowserRouter>
    )
}


5. Finally add it to the correct virtual DOM in index.js as shown.

Index.js


const root = ReactDOM
                    .createRoot(document
                                  .getElementById('root'));

root.render(
  <React.StrictMode>  
   <Container/>
  </React.StrictMode>
);
To execure, be sure you have navigated to your project directory from command terminal  
          






This completes the integration, using Hooks and the @reduxjs/toolkit

  

When executed, the output should look as follows

CLICK BUY ICECREAM