WCF Client-Server NullReferenceException - asp.net

Ok, here's the problem i've been dealing with the whole day:
I'm building a web application forms using WCF Data Service and XPO as ORM Data Model in the server side which contains a method, and in the client side, i'm trying to add a line to a database from a web form after authenfitication.
The user can log in without problems with this code:
try
{
ctx = null;
ctx = new XpoContext(serviceRootUri);
ctx.Credentials = new NetworkCredential(UserName.Text, UserPass.Text);
var res = ctx.Users.FirstOrDefault();
FormsAuthentication.RedirectFromLoginPage(UserName.Text, Persist.Checked);
}
catch (SecurityException ex)
{
Msg.Text = "Erreur: " + ex.Message;
}
}
now i want to add a line to a database with this code:
Uri u = new Uri(string.Format(LogIn.ctx.BaseUri + "/CreateUser?name='{0}'&pass='{1}'",
New_UserName.Text, New_UserPass.Text), UriKind.RelativeOrAbsolute);
LogIn.ctx.Execute(u, "GET");
ServiceReference1.Users user = new ServiceReference1.Users();
user.Nom = New_UserName.Text;
user.Pass = New_UserPass.Text;
LogIn.ctx.AddToUsers(user);
LogIn.ctx.SaveChanges();
but after executing in the 1st two lines an exception occurs.
i'm declaring my context as static in the logIn page:
private static Uri serviceRootUri = new Uri("http://localhost:28748/WcfDataService1.svc/");
public static XpoContext ctx;
As u can see i call my context in the adduser web form with LogIn.ctx ( the same context in the log in page )
Thanks

Related

How to get claims from Azure AD B2C

I have followed the following tutorial
Azure AD B2C: Call an ASP.NET Web API from an ASP.NET Web App
I am able to run the app.
When the authorisation code is received I put a break point on line var code = notification.Code;and I am able to see all the claims received.
But when I try to print the claims nothing is displayed and the app exits. It shows a null object reference on the following line
string a = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Country).Value;
Any idea how I can print all the claims. Any help will be appreciated. Thank you
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
{
// Extract the code from the response notification
var code = notification.Code;
string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
string a = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Country).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
ConfidentialClientApplication cca = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential(ClientSecret), userTokenCache, null);
try
{
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes);
}
catch (Exception ex)
{
//TODO: Handle
throw;
}
}

How to pass connection string name from Silverlight Application to DomainService

First I want to say I'm not SL developer. I just need to modify one legacy Silverlight 5 application.
It is using RIA services and XAP is hosted in Asp.Net page.
User on login page enters credentials and is able to select database from dropdown. Whole web is using multiple connections and user is able to select database to connect.
This selected database (or any identificator for data connection) is sent do XAP's InitParams, so I can access it from SL.
private void Application_Startup(object sender, StartupEventArgs e)
{
foreach (var item in e.InitParams)
{
Resources.Add(item.Key, item.Value);
}
var selectedConnectionString = GetInitParam("ConnectionString");
// TODO: Different way to store connection string
SetCookie("ConnectionString", selectedConnectionString);
RootVisual = new LoadingPage();
}
Currently I'm trying to use cookie to store selected database. I found it somewhere as one possible solution. But it needs to change.
Ok, then we have DomainService.
public class CommissionDomainService : LinqToEntitiesDomainService<CommissionEntitiesContext>
{
...
}
I know that I need to use CreateObjectContext to change ConnectionString in service. So I have:
protected override CommissionEntitiesContext CreateObjectContext()
{
// TODO: Different way to store connection string
string connectionStringName;
if (System.Web.HttpContext.Current.Request.Cookies["ConnectionString"] != null)
{
connectionStringName = System.Web.HttpContext.Current.Request.Cookies["ConnectionString"].Value;
}
else
{
throw new Exception("Missing connectionStringName");
}
var connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
var entityCs = new EntityConnectionStringBuilder
{
Metadata = "res://*/CommissionEntities.csdl|res://*/CommissionEntities.ssdl|res://*/CommissionEntities.msl",
Provider = connectionStringSettings.ProviderName,
ProviderConnectionString = connectionStringSettings.ConnectionString
};
return new CommissionEntitiesContext(entityCs.ConnectionString);
}
Again, I used Cookie to pass value from application to service.
But it is not the best idea. Because of cookie and because of persistance etc.
My question is, how to pass my ConnectionString value from main application to DomainService? Or Can I access some application context from service? Or maybe can I get connection string somewhere in EntitiesContext?
Ok, I did it this way.
I made selected database part of user identity. Because I'm using Owin, I just used one of Claims.
So when user logs in, I just put one claim with selected database
// build a list of claims
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.UserData, selectedDatabase)
};
// create the identity
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);
// sign in
Context.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
Then in DomainService I used Initialize and CreateObjectContext methods
private string _connectionStringName;
public override void Initialize(DomainServiceContext context)
{
// Načteme z kontextu usera zvolenou databázi
var claim = ((ClaimsIdentity)context.User.Identity).FindFirst(ClaimTypes.UserData);
_connectionStringName = claim.Value;
base.Initialize(context);
...
}
protected override CommissionEntitiesContext CreateObjectContext()
{
if (string.IsNullOrEmpty(_connectionStringName))
{
throw new Exception("Missing connectionStringName");
}
var connectionStringSettings = ConfigurationManager.ConnectionStrings[_connectionStringName];
var entityCs = new EntityConnectionStringBuilder
{
Metadata = "res://*/CommissionEntities.csdl|res://*/CommissionEntities.ssdl|res://*/CommissionEntities.msl",
Provider = connectionStringSettings.ProviderName,
ProviderConnectionString = connectionStringSettings.ConnectionString
};
return new CommissionEntitiesContext(entityCs.ConnectionString);
}

Using Web.Api to asynchronously log errors for asp.net mvc

I have a legacy logging DLL that logs errors into a database. Instead of consuming the DLL within each application in our environment, we would like to make web calls to log errors.
I have built up a web.api app that will log errors into a database. When tested with POSTMAN it works as advertised.
I have added a class within a demo MVC app and wired up one of my constructors to execute a log command, but the call not only does not make it to my web.api, but fiddler does not show a call even being made.
Any input on making this actually run would be greatly appreciated.
Here's my code:
Logging Utility Called within Web.API
public class Utilities
{
public void LogException(string exceptionMessage, string stackTrace, string appCode, string runMode, int entityId, int itmsUserID, string updateBy, string path, string method)
{
ErrorLog.Entry _error = new ErrorLog.Entry();
_error.ErrorMessage = exceptionMessage;
_error.StackTrace = stackTrace;
_error.AppCode = appCode;
_error.Path = path;
_error.Method = method;
_error.UpdateBy = updateBy;
_error.RunMode = runMode;
_error.EntityID = entityId;
//_error.Server = server; server will have to be changed to accept a setter
_error.ITMSUserID = CommonFunctions.Get_ITMSUserID(updateBy);
_error.Save();
}
}
Web.API
// POST: api/ErrorLog
public void Post([FromBody]ErrorLogEntryDTO item)
{
var utils = new Utilities();
utils.LogException(item.ErrorMessage, item.StackTrace, item.AppCode, item.RunMode, item.EntityID, item.ITMSUserID, item.UpdateBy, item.Path, item.Method);
}
MVC Controller Code
// GET: BillingRules/Create
public virtual ActionResult CauseHandledError()
{
try
{
throw new Exception("Handled exception test");
}
catch (Exception ex)
{
var utils = new Utilities();
utils.LogException(ex, "system", MVC.BillingRules.Name, MVC.BillingRules.ActionNames.CauseHandledError);
}
return RedirectToAction(MVC.BillingRules.ActionNames.Index, MVC.BillingRules.Name);
}
Utilities Code within MVC App
public void LogException(Exception exception, string updateBy, string path, string method)
{
try
{
var itmsUserID = CommonFunctions.Get_ITMSUserID(updateBy);
var errorDTO = new ErrorLogEntryDTO();
errorDTO.ITMSUserID = itmsUserID;
errorDTO.AppCode = _appCode.Value;
errorDTO.ErrorMessage = exception.Message;
errorDTO.StackTrace = exception.StackTrace;
errorDTO.Path = path;
errorDTO.Method = method;
errorDTO.UpdateBy = updateBy;
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:52316");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var result = client.PostAsJsonAsync("api/ErrorLog", errorDTO).Result; //ContinueWith(readTask => client.Dispose()); //
}
catch (Exception ex)
{
var myError = ex;
throw;
}
}
I'm pretty sure calling .Result in this instance does not immediately invoke the PostAsJsonAsync method. Because you're not doing anything with the Result, it never actually executes. Since it doesn't appear you care about the response, you should be able to use:
client.PostAsJsonAsync("api/ErrorLog", errorDTO).Wait();
I think .Result invokes the PostAsJsonAsync call. You are waiting for the respsonse, so the call must be finished after this line. Regardless if you use the Result or not.
You can remove the [FromBody] attribute, because the complex type is per default read from the body.
And I can't reproduce your issue. I've created a new Web API project and a new console project. In the Web API I've changed the post of the valuescontroller to yours.
In the console project I'm yousing your LogException() method from the MVC app.
It hits my web api app.
Are both in the same host or in different hosts?
Edit:
To make your logging async you can use fire-and-forget with Task.Run() but it depends on the application you have. In ASP.Net Task.Run() is an anti-pattern according to Task.Run Etiquette Examples: Don't Use Task.Run in the Implementation.

Accessing SSRS server report from local application

I have deployed my SSRS reports in the server. Is it possible for me to access that report from my local web application. I have given the server's credentials in the web.config. But still its not displaying the report and it shows some error like Cannot create a connection to data source 'DataSource1'. (rsErrorOpeningConnection).
When I hosted the same application in the server it is working absolutely fine.
Can anyone tell me why am not able to access the reports from my local system?
This is not my code, but ideally is all you have to do. I remember using it successfully in one of previous projects some time back
private void ShowReport()
{
try
{
string urlReportServer = "http://sqlDBServer//Reportserver";
rptViewer.ProcessingMode = ProcessingMode.Remote; // ProcessingMode will be Either Remote or Local
rptViewer.ServerReport.ReportServerUrl = new Uri(urlReportServer); //Set the ReportServer Url
rptViewer.ServerReport.ReportPath = "/ReportName"; //Passing the Report Path
//Creating an ArrayList for combine the Parameters which will be passed into SSRS Report
ArrayList reportParam = new ArrayList();
reportParam = ReportDefaultPatam();
ReportParameter[] param = new ReportParameter[reportParam.Count];
for (int k = 0; k < reportParam.Count; k++)
{
param[k] = (ReportParameter)reportParam[k];
}
// pass crendentitilas
//rptViewer.ServerReport.ReportServerCredentials =
// new ReportServerCredentials("uName", "PassWORD", "doMain");
//pass parmeters to report
rptViewer.ServerReport.SetParameters(param); //Set Report Parameters
rptViewer.ServerReport.Refresh();
}
catch (Exception ex)
{
throw ex;
}
}
Ref: http://www.codeproject.com/Articles/675762/Call-SSRS-Reports-by-using-Csharp

WCF Synchronous vs Asynchronous

I have been looking at MSDN and codeproject, but I am still a bit confused.
Synchronous Service vs an Asynchronous service.
I have a WCF service end point. This service has a 2way SSL applied to its web.config file.
The client end point is a Oracle based java Weblogic Suite. This has its own private key and public key. The client needs to communicate with our service both asynchronously and synchronously.
I CAN ONLY CHANGE THINGS ON THE SERVER SIDE
http://www.codeproject.com/Articles/91528/How-to-Call-WCF-Services-Synchronously-and-Asynchr
http://msdn.microsoft.com/en-us/library/ms731177.aspx
The following code is the synchronous part of the SVC, cs file:-
public getQuoteSyncResponse1 getQuoteSync(getQuoteSyncRequest request)
{
// Create new response
getQuoteSyncResponse1 res = new getQuoteSyncResponse1();
res.GetQuoteSyncResponse = new GetQuoteSyncResponse();
res.GetQuoteSyncResponse.Header = new GetQuoteResponseHeaderType();
res.GetQuoteSyncResponse.Response = new GetQuoteSyncResponseType();
// Create and populate header
res.GetQuoteSyncResponse.Header.MessageId = request.GetQuoteRequestSync.Header.MessageId;
res.GetQuoteSyncResponse.Header.Timestamp = request.GetQuoteRequestSync.Header.Timestamp;
res.GetQuoteSyncResponse.Header.QuoteId = request.GetQuoteRequestSync.Header.QuoteId;
res.GetQuoteSyncResponse.Header.CarrierId = request.GetQuoteRequestSync.Header.CarrierId;
List<RejectionType> rj = new List<RejectionType>();
string _sTotalEmployees = request.GetQuoteRequestSync.Request.Employer.TotalEmployees;
int _TotalEmployees = 0;
if (int.TryParse(_sTotalEmployees, out _TotalEmployees) == false)
{
RejectionType rt;
rt = new RejectionType();
rt.ReasonCode = "R01";
rt.ReasonDescription = "Invalid Number of Employees";
rj.Add(rt);
res.GetQuoteSyncResponse.Response.Rejections = rj.ToArray();
res.GetQuoteSyncResponse.Response.ReceiptStatus = AcceptanceContentType.Reject;
return res;
}
res.GetQuoteSyncResponse.Response.ReceiptStatus = AcceptanceContentType.Success;
List<QuoteType> q = new List<QuoteType>();
QuoteType qt;
qt = new QuoteType();
qt.PlanId = "P345678";
qt.EEPremium = 1220;
qt.EESPPremium = 2222;
qt.EEDepPremium = 3333;
qt.EEFamilyPremium = 4444;
qt.TotalMonthlyPremium = 3456;
qt.CoverageEffectiveDate = DateTime.Now;
q.Add(qt);
res.GetQuoteSyncResponse.Response.Quotes = q.ToArray();
return res;}
so this Synchronous part of the service is working. Now, how do I use this to transform it into the asynchronous equivalent?
Should I be starting the async method in the cs file? or in the svc file? I am confused...
public getQuoteAsyncResponse getQuoteAsync(getQuoteAsyncRequest request, AsyncCallback callback, Object state)
{
// Create new response
getQuoteAsyncResponse res = new getQuoteAsyncResponse();
return new getQuoteAsyncResponse();
}
I sort of understand about the callback deli-gator, object state and such, but can someone illustrate this further for me? How do I format the asynchronous part of the service? The web has so many examples... but all very confusing. I must have some inherent misunderstanding on this concept.
Edit:- I was told in the answer that, the server side needs no manipulation for async style of communication. However I found this:-
Implementing Asynchronous Operations in WCF
Just as the WCF plumbing enables clients to call server operations asynchronously, without the server needing to know anything about it, WCF also allows service operations to be defined asynchronously. So an operation like:
[OperationContract]
string DoWork(int value);
…might instead be expressed in the service contract as:
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginDoWork(int value, AsyncCallback callback, object state);
string EndDoWork(IAsyncResult result);
Note that the two forms are equivalent, and indistinguishable in the WCF metadata: they both expose an operation called DoWork[1]:
The async part needs to be done in the client. This means you are probably doing something similar to:
var response = ServiceReference.GetSomething();
Instead, make a proxy to get the callback. Create and event (or delegate) that gets fired (or called) whenever the callback receives the response. In the above statement, you are obviously waiting for the response to be assigned into the variable before moving to the next line.
Instead, you could
On the Service contract, be sure to decorate with [OperationContract(IsOneWay = true)]
If you use ServiceReference or serviceutil, it will automatically create "incoming events" and do all the client side async work for you.
If you are using TCP, create an callback contract as well, then on client you can do something like
ServiceReference1.IncomingSomething += new eventHandler.
Now you can do ServiceReferecnce1.GetSomething(), and the response will go to the eventhandler function.
If this is RESTFUL:
public void MakeAsyncRequest(string url, string contentType)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = WebRequestMethods.Http.Get;
request.Timeout = 10000;
request.Proxy = null;
request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
}
catch (Exception ex)
{
LogManager.LogException(ex);
}
}
private void ReadCallback(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
string strContent = string.Empty;
string s;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult))
{
Stream responseStream = response.GetResponseStream();
using (StreamReader sr = new StreamReader(responseStream))
{
//Need to return this response
strContent = sr.ReadToEnd();
}
}
}
catch (Exception ex)
{
throw;
}
}

Resources