SqlCacheDepency.. QueryNotification subscription not working - sql-server

public class MemoryCacheHelper
{
private static string _conn = ConfigurationManager.ConnectionStrings["EFMultiPoolDbContext"] != null ?
ConfigurationManager.ConnectionStrings["EFMultiPoolDbContext"].ConnectionString :
ConfigurationManager.ConnectionStrings["EFDbContext"].ConnectionString;
private static Logger _logger = LogManager.GetCurrentClassLogger();
private static int _hourOfExpiry = 8; // ConfigurationHelper.GetValue<int>("Cache:HourExpiry", 8);
//private static SqlDependency dependency;
private static ObjectCache _cache = MemoryCache.Default;
private static WebCaching.Cache _webcache = new WebCaching.Cache();
private ReaderWriterLockSlim _cachelock = null;
public MemoryCacheHelper()
{
_cachelock = new ReaderWriterLockSlim();
EnoughPermission();
}
public void Add(string key, object val)
{
Add(key, val, new CacheItemPolicy()
{
SlidingExpiration = new TimeSpan(_hourOfExpiry, 0, 0)
});
}
public void Add(string key, object val, int seconds)
{
Add(key, val, new CacheItemPolicy()
{
//SlidingExpiration = new TimeSpan(0,0,seconds)
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(seconds))
});
}
public void Add(string key, object val, int mins, WebCaching.CacheDependency dependency)
{
if (val == null)
return;
//_cachelock.EnterReadLock();
try
{
//if (_cache1.Get(key) != null)
{
_logger.Debug(string.Format("Cache Key: {0} set at {1}", key, DateTime.Now));
_webcache.Insert(key, val, dependency, WebCaching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(mins),
WebCaching.CacheItemPriority.Default, CacheItemRemovedCallback);
//if (key == "productTypes")
// _logger.Debug(string.Format("Cache Key: {0} set at {1}", key, DateTime.Now));
}
}
finally
{
// _cachelock.ExitReadLock();
}
}
public static T CheckOrRequeryWebCache<T>(string key, int mins, string commandText)
{
var cache = new MemoryCacheHelper();
object res = cache.GetWebCacheItem(key);
if (res == null)
{
SqlDependency.Stop(_conn);
SqlDependency.Start(_conn);
using (var con = new SqlConnection(_conn))
{
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.Notification = null;
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.CommandText=#"SET ANSI_NULLS ON;SET ANSI_PADDING ON;SET ANSI_WARNINGS ON;SET CONCAT_NULL_YIELDS_NULL ON;SET QUOTED_IDENTIFIER ON;SET NUMERIC_ROUNDABORT OFF;SET ARITHABORT ON;";
{
cmd.ExecuteNonQuery();
}
cmd.CommandText = commandText;
var ds = new DataSet();
da.Fill(ds);
if (key == "visualIdPLUs")
res = ds.Tables[0].AsEnumerable().Select(x => Convert.ToString(x["ParentPLU"])).ToList();
else
res = ds.Tables[0].AsEnumerable().Select(x => new BlockedGIdDateExchangePLU
{
PLU = Convert.ToString(x["ParentPLU"]),
CanExchangeDate = Convert.ToBoolean(x["CanExchangeDate"]),
CanExchangeGId = Convert.ToBoolean(x["CanExchangeGId"])
}).ToList();
var dependency = new WebCaching.SqlCacheDependency(cmd);
//dependency = new SqlDependency(cmd);
//dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
cache.Add(key, res, mins, dependency);
}
}
}
return (T)res;
}
private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
}
private bool EnoughPermission()
{
SqlClientPermission perm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
try
{
perm.Demand();
return true;
}
catch (System.Exception)
{
return false;
}
}
}
profiler trace for working sample profiler trace for my main projectAm working on SqlCacheDependency. i need to implement it in my main project
in order to test first , i have created sample MVC project and implemented is working perfectly fine, can see all the QueryNotification events on profiler.
when am trying to run the same code in my main project is not working.. the problem i found out from sql profiler is not all qn events are firing.. starting from susbscription event.
can anyone please suggest what is wrong.. (note: am using same database and sql login for both sample and main project)

Related

Can't recieve byte array using Retrofit 2 in Kotlin

I have a DTO class using Moshi that's supposed to send and recieve byte arrays[], but it only works when sending them, because when I recieve then I have this exception.
com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was STRING at path $[0].image
But im pretty sure that the type that the API returns is a byte array.
Here's the DTO class and API controller
#JsonClass(generateAdapter = true)
data class LocationImageDTO (
#Json(name="idLocationImage") val idLocationImage: Int,
#Json(name = "idLocation") val idLocation: Int?,
#Json(name="image") val image: ByteArray,
)
//This one is for recieving
public List<clsLocationImage> getList(int idLocation)
{
List<clsLocationImage> list = new List<clsLocationImage>();
clsLocationImage locationImage;
clsMyConnection connection = new clsMyConnection();
SqlCommand command = new SqlCommand
{
CommandText = "SELECT idLocationImage, idLocation, image FROM K0_MAP_LOCATION_IMAGES WHERE idLocation = #idLocation",
Connection = connection.getConnection()
};
command.Parameters.Add("#idLocation", System.Data.SqlDbType.Int).Value = idLocation;
SqlDataReader reader;
try
{
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
locationImage = new clsLocationImage();
locationImage.idLocationImage = (int)reader["idLocationImage"];
locationImage.idLocation = (int)reader["idLocation"];
locationImage.image = (byte[])reader["image"];
list.Add(locationImage);
}
}
}
catch (SqlException excepcion)
{
throw excepcion;
}
return list;
}
public List<clsLocationImage> getListDAL(int id)
{
return getList(id);
}
}
}
///This one is for sending
public int createLocationImage(clsLocationImage locationImage)
{
int filasAfectadas = 0;
clsMyConnection conexion = new clsMyConnection();
SqlCommand miComando = new SqlCommand
{
CommandText = "INSERT INTO K0_MAP_LOCATION_IMAGES(idLocation, image) VALUES (#idLocation, #image)",
Connection = conexion.getConnection()
};
miComando.Parameters.Add("#idLocation", System.Data.SqlDbType.Int).Value = locationImage.idLocation;
miComando.Parameters.Add("#image", System.Data.SqlDbType.VarBinary).Value = locationImage.image;
try
{
filasAfectadas = miComando.ExecuteNonQuery();
}
catch (SqlException excepcion)
{
throw excepcion;
}
return filasAfectadas;
}
}
}
You need to set an explicit JSON adapter to the Moshi Builder.
class CustomDateAdapter : JsonAdapter<Date>() {
private val dateFormat = SimpleDateFormat(SERVER_FORMAT, Locale.getDefault())
#FromJson
override fun fromJson(reader: JsonReader): Date? {
return try {
val dateAsString = reader.nextString()
synchronized(dateFormat) {
dateFormat.parse(dateAsString)
}
} catch (e: Exception) {
null
}
}
#ToJson
override fun toJson(writer: JsonWriter, value: Date?) {
if (value != null) {
synchronized(dateFormat) {
writer.value(value.toString())
}
}
}
companion object {
const val SERVER_FORMAT = ("yyyy-MM-dd'T'HH:mm") // define your server format here
}
}
And then you add it in the Moshi builder
private val moshiBuilder = Moshi.Builder().add(CustomDateAdapter())
private fun getRetrofit(): Retrofit =
Retrofit.Builder()
.baseUrl(MAPK0_API_BASE_URL)
.addConverterFactory(MoshiConverterFactory.create(moshiBuilder.build()))
//.client(getUnsafeOkHttpClient())
.build()
}

.net c# WebChannelFactory keepAliveEnabled=false with webHttpBehavior

I create WebChannelFactory. I need set KeepAlive=false.
I found only one solution use CustomBinding. and set property keepAliveEnabled to false.
I use custom behavior for my factory also.
Code:
static CustomBinding GetBinding(MySettings serviceSettings = null)
{
var customBinding = new CustomBinding();
HttpTransportBindingElement transportBindingElement = new HttpTransportBindingElement();
transportBindingElement.KeepAliveEnabled = false;
transportBindingElement.MaxBufferSize = 0x07000000;
transportBindingElement.MaxReceivedMessageSize = 0x07000000;
if (serviceSettings != null)
{
customBinding.SendTimeout = serviceSettings.SendTimeout;
}
customBinding.Elements.Add(transportBindingElement);
return customBinding;
}
var customBinding = GetBinding(serviceSettings);
WebChannelFactory<TChannel> factory = new WebChannelFactory<TChannel>(customBinding, new Uri(url));
factory.Endpoint.Behaviors.Add(new MyWebHttpBehavior(userId));
class MyWebHttpBehavior : IEndpointBehavior
{
private int _userId;
public MyWebHttpBehavior(int userId)
{
_userId = userId;
}
public void AddBindingParameters(ServiceEndpoint serviceEndpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{ }
public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, System.ServiceModel.Dispatcher.ClientRuntime behavior)
{
behavior.MessageInspectors.Add(new MyClientMessageInspector(_userId));
}
public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{ }
public void Validate(ServiceEndpoint serviceEndpoint)
{ }
}
In current situation i get error "does not have a Binding with the None MessageVersion".

Dapper table valued parameter as a property?

I have a stored proc like this:
CREATE PROCEDURE [dbo].[Organisation_Insert]
#OrganisationXId uniqueidentifier
,#Enabled bit
,#Timezone nvarchar(50)
,#MinimumValue float
,#Rules ReminderRuleType READONLY ...
ReminderRuleType is a user defined type.
In my app I have this:
class OrganisationDTO
{
private readonly IOrganisationDocument _orgDoc;
public long OrganisationId { get { return _orgDoc.OrganisationId; } }
public Guid OrganisationXId { get { return _orgDoc.OrganisationXId; } }
public string TimeZone { get { return _orgDoc.TimeZone; } }
public bool Enabled { get { return _orgDoc.Enabled; } }
public decimal MinimumValue { get { return _orgDoc.MinimumValue; } }
public RuleTableValuedParameters Rules { get; private set; }
public OrganisationDTO(IOrganisationDocument orgDoc)
{
_orgDoc = orgDoc;
Rules = new RuleTableValuedParameters("#Rules", _orgDoc.Rules);
}
}
RuleTableValuedParameters implements SqlMapper.IDynamicParameters which has an AddParameters method.
When I execute the query, the #Rules parameter is never passed (using SQLProfiler). I can also see that AddParameters is never called.
Is this possible to do?
Thanks
Here's a simplified example based on your code that shows it working just fine; AddParameters is invoked correctly, and the values are conveyed to the stored procedure. As a side note: if you are using DataTable for your TVPs, the library supports that directly with no additional code needed.
public void SO29596645_TvpProperty()
{
try { connection.Execute("CREATE TYPE SO29596645_ReminderRuleType AS TABLE (id int NOT NULL)"); }
catch { }
connection.Execute(#"create proc #SO29596645_Proc (#Id int, #Rules SO29596645_ReminderRuleType READONLY)
as begin select #Id + ISNULL((select sum(id) from #Rules), 0); end");
var obj = new SO29596645_OrganisationDTO();
int val = connection.Query<int>("#SO29596645_Proc", obj.Rules, commandType: CommandType.StoredProcedure).Single();
// 4 + 9 + 7 = 20
val.IsEqualTo(20);
}
class SO29596645_RuleTableValuedParameters : Dapper.SqlMapper.IDynamicParameters {
private string parameterName;
public SO29596645_RuleTableValuedParameters(string parameterName)
{
this.parameterName = parameterName;
}
public void AddParameters(IDbCommand command, Dapper.SqlMapper.Identity identity)
{
Console.WriteLine("> AddParameters");
SqlCommand lazy = (SqlCommand)command;
lazy.Parameters.AddWithValue("Id", 7);
DataTable table = new DataTable {
Columns = {{"Id", typeof(int)}},
Rows = {{4}, {9}}
};
lazy.Parameters.AddWithValue("Rules", table);
Console.WriteLine("< AddParameters");
}
}
class SO29596645_OrganisationDTO
{
public SO29596645_RuleTableValuedParameters Rules { get; private set; }
public SO29596645_OrganisationDTO()
{
Rules = new SO29596645_RuleTableValuedParameters("#Rules");
}
}
Here's the full working DynamicParameter that I created:
public class OrganisationDynamicParameter : SqlMapper.IDynamicParameters
{
private readonly IOrganisation _orgModel;
public OrganisationDynamicParameter(IOrganisation orgModel)
{
_orgModel = orgModel;
}
public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
SqlParameter p;
var sqlCommand = (SqlCommand)command;
sqlCommand.CommandType = CommandType.StoredProcedure;
p = sqlCommand.Parameters.Add("#OrganisationXId", SqlDbType.UniqueIdentifier);
p.Value = _orgModel.OrganisationXId;
p = sqlCommand.Parameters.Add("#Enabled", SqlDbType.Bit);
p.Value = _orgModel.Enabled;
p = sqlCommand.Parameters.Add("#Timezone", SqlDbType.NVarChar, 50);
p.Value = _orgModel.TimeZone;
p = sqlCommand.Parameters.Add("#MinimumValue", SqlDbType.Float);
p.Value = _orgModel.MinimumValue;
List<SqlDataRecord> ruleList = _orgModel.Rules.Select(MapRuleData).ToList();
if (ruleList.Count > 0)
{
p = sqlCommand.Parameters.Add("#Rules", SqlDbType.Structured);
p.Direction = ParameterDirection.Input;
p.TypeName = "ReminderRuleType";
p.Value = ruleList;
}
}
protected SqlDataRecord MapRuleData(IReminderRule value)
{
var rec = new SqlDataRecord(new[]
{
new SqlMetaData("RuleId", SqlDbType.BigInt),
new SqlMetaData("OrganisationId", SqlDbType.BigInt),
new SqlMetaData("Name", SqlDbType.NVarChar, 200),
new SqlMetaData("OffsetDays", SqlDbType.Int),
new SqlMetaData("SubjectTemplate", SqlDbType.NVarChar, -1),
new SqlMetaData("BodyTemplate", SqlDbType.NVarChar, -1)
});
rec.SetInt64(0, value.RuleId);
rec.SetInt64(1, value.OrganisationId);
rec.SetString(2, value.Name);
rec.SetInt32(3, value.OffsetDays);
rec.SetString(4, value.SubjectTemplate);
rec.SetString(5, value.BodyTemplate);
return rec;
}
}
I use this thusly:
public IOrganisation CreateOrganisation(IOrganisation organisation)
{
var dtoOrg = new OrganisationDynamicParameter(organisation);
return ExecuteSPReturningOrganisation("Organisation_Insert", dtoOrg);
}
protected IOrganisation ExecuteSPReturningOrganisation(string query, object parameters)
{
using (IDbConnection con = ConnectionFactory.CreateOpenConnection())
{
using (
SqlMapper.GridReader multi = con.QueryMultiple(query, parameters,
commandType: CommandType.StoredProcedure))
{
OrganisationModel org = multi.Read<OrganisationModel>().SingleOrDefault();
if (org != null)
{
org.Rules = multi.Read<ReminderRuleModel>().ToArray();
}
return org;
}
}
}
Cheers

Is there a utility to dump an existing log4j log file into a relational database?

Seems, like a very basic thing, but I could not find it.
I have a bunch of log4j/log4net log files. I would like to dump them into a database in order to be able to analyze them with ease.
I thought I would find a tool to do it in no time, apparently I am wrong.
Does anyone know of such a tool?
OK, so I found no utility. Had to write my own. Of course, it is strictly tailored to my immediate needs (time is money), however, it can save you a bit of time to start your own, in case of a need. Here is the complete code in C#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication3
{
class Program
{
public class LogEntry
{
private const string PATTERN = #"^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{4}) (\S+) \[(\d+)\] (\w+) (\S+) - (.*)$";
private static readonly Regex s_regex = new Regex(PATTERN, RegexOptions.Compiled);
public DateTime TS;
public string Machine;
public int Thread;
public string Level;
public string Logger;
public string Message;
public static LogEntry TryCreate(string line)
{
var match = s_regex.Match(line);
return match.Success ? new LogEntry
{
TS = DateTime.ParseExact(match.Groups[1].Value, "yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture),
Machine = match.Groups[2].Value,
Thread = int.Parse(match.Groups[3].Value),
Level = match.Groups[4].Value,
Logger = match.Groups[5].Value,
Message = match.Groups[6].Value,
} : null;
}
public void AppendToMessage(string line)
{
Message += Environment.NewLine + line;
}
}
static void Main()
{
const string SQL = #"
INSERT INTO log ( ts, machine, thread, level, logger, message, journalId)
VALUES (#ts, #machine, #thread, #level, #logger, #message, #journalId)
";
using (var connection = new SqlConnection("server=localhost;database=misc;uid=SantaClaus;pwd=MerryChristmas"))
{
connection.Open();
using (var command = new SqlCommand(SQL, connection))
{
var tsParam = new SqlParameter("#ts", SqlDbType.DateTime);
var machineParam = new SqlParameter("#machine", SqlDbType.NVarChar, 32);
var threadParam = new SqlParameter("#thread", SqlDbType.Int);
var levelParam = new SqlParameter("#level", SqlDbType.NVarChar, 10);
var loggerParam = new SqlParameter("#logger", SqlDbType.NVarChar, 128);
var messageParam = new SqlParameter("#message", SqlDbType.NVarChar, -1);
var journalIdParam = new SqlParameter("#journalId", SqlDbType.Int);
command.Parameters.Add(tsParam);
command.Parameters.Add(machineParam);
command.Parameters.Add(threadParam);
command.Parameters.Add(levelParam);
command.Parameters.Add(loggerParam);
command.Parameters.Add(messageParam);
command.Parameters.Add(journalIdParam);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
int i = 0;
foreach (var file in Directory.GetFiles(#"c:\tmp\dfbje01"))
{
journalIdParam.Value = OpenJournal(connection, file);
command.Transaction = connection.BeginTransaction();
foreach (var e in GetLogEntries(file))
{
tsParam.Value = e.TS;
machineParam.Value = e.Machine;
threadParam.Value = e.Thread;
levelParam.Value = e.Level;
loggerParam.Value = e.Logger;
messageParam.Value = e.Message;
command.ExecuteNonQuery();
++i;
if (i == 1000)
{
i = 0;
command.Transaction.Commit();
command.Transaction = connection.BeginTransaction();
}
}
command.Transaction.Commit();
CloseJournal(connection, journalIdParam.Value);
}
}
}
}
private static void CloseJournal(SqlConnection connection, object id)
{
const string SQL = "UPDATE journal SET done = 1 WHERE id = #id";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#id", id));
command.ExecuteNonQuery();
}
}
private static object OpenJournal(SqlConnection connection, string filePath)
{
const string SQL = "INSERT INTO journal (filePath) OUTPUT inserted.id VALUES (#filePath)";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#filePath", filePath));
return command.ExecuteScalar();
}
}
private static IEnumerable<LogEntry> GetLogEntries(string filePath)
{
LogEntry prev = null;
foreach (var line in File.ReadLines(filePath))
{
var logEntry = LogEntry.TryCreate(line);
if (logEntry != null)
{
if (prev != null)
{
yield return prev;
}
prev = logEntry;
}
else if (prev != null)
{
prev.AppendToMessage(line);
}
else
{
// Oops
Console.WriteLine(line);
}
}
if (prev != null)
{
yield return prev;
}
}
}
}
Mind trying out the filtering, search, colorizing features of the latest developer snapshot of Chainsaw? It has a good number of features which may avoid the need to use a DB. If you use a VFSLogFilePatternReceiver, it can parse and tail any regular text file, including those created by log4net.
Latest developer snapshot of Chainsaw is available here:
http://people.apache.org/~sdeboy

Async call of WCF using Duplex Communication to get Database change

I am implementing and WCF Async service using WsDualHttpBinding binding for duplex communication to get database changes.
I have implemented the Service but I dont know how to call it from Client application.
Here is the code.
The below code is WCF Service
[ServiceContract()]
public interface ICustomerService
{
[OperationContract(IsOneWay = true)]
void GetAllCustomer();
}
public interface ICustomerServiceCallback
{
[OperationContract(IsOneWay = true)]
void Callback(Customer[] customers);
}
[ServiceContract(Name = "ICustomerService",
CallbackContract = typeof(CustomerServiceLibrary.ICustomerServiceCallback),
SessionMode = SessionMode.Required)]
public interface ICustomerServiceAsync
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginGetAllCustomer(AsyncCallback callback, object asyncState);
void EndGetAllCustomer(IAsyncResult result);
}
[DataContract]
public class Customer
{
[DataMember]
public string Name
{
get;
set;
}
}
}
public class CustomerService :ICustomerService,IDisposable
{
List<Customer> Customers = null;
ICustomerServiceCallback callback;
Customer customer = null;
string constr = "Data Source=.;Initial Catalog=WPFCache;Persist Security Info=True;User ID=sa;Password=Password$2";
public CustomerService()
{
callback = OperationContext.Current.GetCallbackChannel<ICustomerServiceCallback>();
SqlDependency.Start(constr);
}
public void GetAllCustomer()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "GetHero";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Notification = null;
// Create the associated SqlDependency
SqlDependency dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(dep_OnChange);
SqlDataReader dr = cmd.ExecuteReader();
Customers = new List<Customer>();
while (dr.Read())
{
customer = new Customer();
customer.Name = dr.GetString(0);
Customers.Add(customer);
}
}
callback.Callback(Customers.ToArray());
}
}
void dep_OnChange(object sender, SqlNotificationEventArgs e)
{
try
{
if (e.Type == SqlNotificationType.Change)
{
GetAllCustomer();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Dispose()
{
SqlDependency.Stop(constr);
}
}
I have hosted this WCF Async Service as self hosting in a Console Application.
Here the hosting code
class Program
{
static void Main(string[] args)
{
StartService();
}
internal static ServiceHost myServiceHost = null;
internal static void StartService()
{
Uri httpbaseAddress = new Uri("http://localhost:8087/CustomerService/");
Uri[] baseAdresses = { httpbaseAddress };
myServiceHost = new ServiceHost(typeof(CustomerServiceLibrary.CustomerService));
myServiceHost.AddServiceEndpoint(typeof(CustomerServiceLibrary.ICustomerService), new WSDualHttpBinding(), httpbaseAddress);
ServiceDescription serviceDesciption = myServiceHost.Description;
foreach (ServiceEndpoint endpoint in serviceDesciption.Endpoints)
{
Console.WriteLine("Endpoint - address: {0}", endpoint.Address);
Console.WriteLine(" - binding name:\t\t{0}", endpoint.Binding.Name);
Console.WriteLine(" - contract name:\t\t{0}", endpoint.Contract.Name);
Console.WriteLine();
}
myServiceHost.Open();
Console.WriteLine("Press enter to stop.");
Console.ReadKey();
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}
In client Application have crated a DuplexChannel factory instance
Here is the Code.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
EndpointAddress address = new EndpointAddress(new Uri("http://localhost:8087/CustomerService"));
WSDualHttpBinding wsDualBinding = new WSDualHttpBinding();
DuplexChannelFactory<ICustomerServiceAsync> client = new DuplexChannelFactory<ICustomerServiceAsync>(new InstanceContext(this), wsDualBinding, address);
App.channel = client.CreateChannel();
}
Now My question is How I can call the
BeginGetAllCustomer
EndGetAllCustomer
Method of My service.
Help me.... A big thanks in Advance ...
You need:
InstanceContext instanceContext = new InstanceContext(YOUR_OBJECT_IMPLMENTS_CALLBACK);
and
using (App.channel as IDisposable)
{
App.channel.YOUR_METHOD_HERE();
}
from this example:
endPointAddr = "net.tcp://" + textBox2.Text + ":8000/FIXMarketDataHub";
NetTcpBinding tcpBinding = new NetTcpBinding();
tcpBinding.TransactionFlow = false;
tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
tcpBinding.Security.Mode = SecurityMode.None;
EndpointAddress endpointAddress = new EndpointAddress(endPointAddr);
Append("Attempt to connect to: " + endPointAddr);
InstanceContext instanceContext = new InstanceContext(??);
IMarketDataPub proxy = DuplexChannelFactory<IMarketDataPub>.CreateChannel(instanceContext,tcpBinding, endpointAddress);
using (proxy as IDisposable)
{
proxy.Subscribe();
Append("Subscribing to market data");
}
See also microsoft example

Resources