.NET Web API is getting null XML from Post - c#

So I am very new to the whole .NET world, so I could very well have some terminology off. I was asked to help with making some changes to this code because I've helped with some other dev work (entirely different systems). Anyway, I can't even get it to run on my test system to begin the actual work - yet they are already using this code in production so I'm assuming it's just an inconsistency in my setup. Either way though I'm trying to drill down into the code to both learn it better and hopefully understand what could be going wrong with my system.
So this API does not have a front end, all of the testing is being done from Postman. It's supposed to post a request with an XML body to a function that then reads the XML and retrieves data. For whatever reason the request that is passed in always comes up NULL, though I think I verified that Postman is submitting the data because I tried the third answer here: Getting raw POST data from Web API method and I do see the full body of the request then.
Here is the method it is posting to:
[Route("summary")]
[ResponseType(typeof(SummarySearchResponseType))]
public IHttpActionResult PostSummary([FromBody] SummarySearchRequestType req)
{
try
{
var response = _searchService.GetSummary(req);
if (response == null)
{
return BadRequest();
}
return Ok(response);
}
catch
{
return StatusCode(System.Net.HttpStatusCode.InternalServerError);
}
}
Here is that SearchService function:
public SummarySearchResponseType GetSummary(SummarySearchRequestType request)
{
Serilog.Log.Information("GetSummary request = {0}", request);
// Validate required fields in request
if (request == null)
{
Serilog.Log.Logger.Warning("One or more required search fields are missing");
return null;
}
if (string.IsNullOrEmpty(request.ClientNumber))
{
Serilog.Log.Logger.Warning("Missing required search field 'ClientNumber'");
return null;
}
if (request.LossDate == null)
{
Serilog.Log.Logger.Warning("Missing required search field 'LossDate'");
return null;
}
var response = new SummarySearchResponseType
{
RequestID = request.RequestID
};
try
{
using (IMultipleResults sprocResults = _dataContext.UspGetDetailedResponse(
request.ClientNumber,
request.PolicyNumber,
request.PolicySuffix,
request.ClientAccountNum,
request.LossDate.ToShortDateString(),
request.PolicyType,
request.LineCode,
request.AgencyCode,
request.Searchtype,
request.Lob,
request.InsuredSearch?.FirstName,
request.InsuredSearch?.LastName,
request.InsuredSearch?.FullName,
request.InsuredSearch?.DBAName,
request.InsuredSearch?.Address.Address1,
request.InsuredSearch?.Address.Address2,
request.InsuredSearch?.Address.City,
request.InsuredSearch?.Address.State,
request.InsuredSearch?.Address.PostalCode,
request.InsuredSearch?.Address.County,
request.InsuredSearch?.Address.Country,
request.InsuredSearch?.ClientAccountnumber,
request.InsuredSearch?.Email,
request.InsuredSearch?.Phone,
request.InsuredSearch?.Comment,
request.RiskUnitSearch?.RiskUnitID,
request.RiskUnitSearch?.RiskUnitName,
request.RiskUnitSearch?.LocationSearch?.BuildingID,
request.RiskUnitSearch?.LocationSearch?.Address?.Address1,
request.RiskUnitSearch?.LocationSearch?.Address?.Address2,
request.RiskUnitSearch?.LocationSearch?.Address?.City,
request.RiskUnitSearch?.LocationSearch?.Address?.State,
request.RiskUnitSearch?.LocationSearch?.Address?.PostalCode,
request.RiskUnitSearch?.LocationSearch?.Address?.County,
request.RiskUnitSearch?.LocationSearch?.Address?.Country,
request.RiskUnitSearch?.VehicleSearch.VIN,
request.RiskUnitSearch?.VehicleSearch.Year,
request.RiskUnitSearch?.VehicleSearch.Make))
{
// Policies
//
var result1 = sprocResults.GetResult<UspGetDetailedResponseResult1>();
var policies = _mapper.Map<IEnumerable<PolicyType>>(result1).ToArray();
// Insured
//
var result2 = sprocResults.GetResult<UspGetDetailedResponseResult2>();
var insured = _mapper.Map<IEnumerable<ParticipantType>>(result2).ToArray();
//Risk Unit
//
var result3 = sprocResults.GetResult<UspGetDetailedResponseResult3>();
var riskUnits = _mapper.Map<IEnumerable<RiskUnitType>>(result3).ToArray();
// Attach Participants and RiskUnits to Policies via PolicyNumber
//
policies.ToList().ForEach(p =>
{
p.Participants = insured.Where(i => i.PolicyNumber == p.PolicyNumber).ToArray();
p.RiskUnits = riskUnits.Where(i => i.PolicyNumber == p.PolicyNumber).ToArray();
});
response.Policies = policies;
response.PolicyCnt = policies.Length.ToString();
Serilog.Log.Information("GetSummary response = {0}", response);
return response;
}
}
catch (Exception ex)
{
Serilog.Log.Error(ex, $"{ex}", ex);
throw ex;
}
}
And here is the SummarySearchRequestType:
public partial class SummarySearchRequestType
{
public override string ToString()
{
XmlSerializer responseSerializer = new XmlSerializer(this.GetType());
using (StringWriter responseWriter = new StringWriter())
{
responseSerializer.Serialize(responseWriter, this);
var xmlResponse = responseWriter.ToString();
return xmlResponse;
}
}
}
And the rest of it:
public partial class SummarySearchRequestType {
private string requestIDField;
private string clientNumberField;
private string policyNumberField;
private string policySuffixField;
private string clientAccountNumField;
private System.DateTime lossDateField;
private bool lossDateFieldSpecified;
private string policyTypeField;
private string lineCodeField;
private InsuredSearchType insuredSearchField;
private RiskUnitSearchType riskUnitSearchField;
private string agencyCodeField;
private string searchtypeField;
private string lobField;
/// <remarks/>
public string RequestID {
get {
return this.requestIDField;
}
set {
this.requestIDField = value;
}
}
/// <remarks/>
public string ClientNumber {
get {
return this.clientNumberField;
}
set {
this.clientNumberField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string PolicyNumber {
get {
return this.policyNumberField;
}
set {
this.policyNumberField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string PolicySuffix {
get {
return this.policySuffixField;
}
set {
this.policySuffixField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string ClientAccountNum {
get {
return this.clientAccountNumField;
}
set {
this.clientAccountNumField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="date")]
public System.DateTime LossDate {
get {
return this.lossDateField;
}
set {
this.lossDateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool LossDateSpecified {
get {
return this.lossDateFieldSpecified;
}
set {
this.lossDateFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string PolicyType {
get {
return this.policyTypeField;
}
set {
this.policyTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string LineCode {
get {
return this.lineCodeField;
}
set {
this.lineCodeField = value;
}
}
/// <remarks/>
public InsuredSearchType InsuredSearch {
get {
return this.insuredSearchField;
}
set {
this.insuredSearchField = value;
}
}
/// <remarks/>
public RiskUnitSearchType RiskUnitSearch {
get {
return this.riskUnitSearchField;
}
set {
this.riskUnitSearchField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string AgencyCode {
get {
return this.agencyCodeField;
}
set {
this.agencyCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string Searchtype {
get {
return this.searchtypeField;
}
set {
this.searchtypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string Lob {
get {
return this.lobField;
}
set {
this.lobField = value;
}
}
}
And in Postman I'm sending a post to the server with this raw XML body:
<?xml version="1.0" encoding="utf-8" ?><SummarySearchRequest xmlns="***"> 
<RequestID>***</RequestID>  <ClientNumber>***</ClientNumber>  <LossDate>***</LossDate>  <PolicyNumber xmlns="***">***</PolicyNumber>
</SummarySearchRequest>
NOTE - I replaced specific data with ***.
Postman is hitting the server, and like I said I was able to verify based on that other post that actual data is getting to the server, but somewhere it is not setting the object properly (or something else). This is running on a VM of windows 11, through IIS Express in Visual Studio which automatically serves the https on port 44375 if that matters. I'd appreciate any insight into what could be the issue, if you need any more information please let me know - I do not understand .NET well yet. Thank you!

Related

Is there a way to deserialize an XML file even if there are missing nodes or more nodes than there should be? C#

I'm working with a lot of XML files that are similar but sometimes each one has more or less nodes. (Let's say that is a billing from a purchase or something like that). But i need to deserialize the XML even when it doesn't match the structure (I need to get common nodes to my class). Node Names won't differ but there may be more nodes than usual
String MainXMLPATH = AppPrincipal.PathDeLecturaIndividual; //Gets xml path from another form
XmlDocument dom = new XmlDocument();
dom.Load(MainXMLPATH); //Loads xml
XmlSerializer serializer = new XmlSerializer(typeof(FacturaElectronica)); //Autogenerated Visual Studio class from XML
FacturaElectronica I;
using (Stream reader = new FileStream(MainXMLPATH, FileMode.Open)) {
// Call the Deserialize method to restore the object's state.
I = (FacturaElectronica)serializer.Deserialize(reader);
}
Console.WriteLine(I.Clave + "," + I.CodigoActividad + "," + I.CondicionVenta + "," + I.DetalleServicio + "," + I.Emisor.CorreoElectronico);//Prints the value of my xml
This is my class:
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "https://cdn.comprobanteselectronicos.go.cr/xml-schemas/v4.3/facturaElectronica")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "https://cdn.comprobanteselectronicos.go.cr/xml-schemas/v4.3/facturaElectronica", IsNullable = false)]
public partial class FacturaElectronica {
private string claveField;
private uint codigoActividadField;
private ulong numeroConsecutivoField;
private System.DateTime fechaEmisionField;
private FacturaElectronicaEmisor emisorField;
private FacturaElectronicaReceptor receptorField;
private byte condicionVentaField;
private byte plazoCreditoField;
private byte[] medioPagoField;
private FacturaElectronicaLineaDetalle[] detalleServicioField;
private FacturaElectronicaOtrosCargos[] otrosCargosField;
private FacturaElectronicaResumenFactura resumenFacturaField;
private Signature signatureField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "integer")]
public string Clave {
get {
return this.claveField;
}
set {
this.claveField = value;
}
}
/// <remarks/>
public uint CodigoActividad {
get {
return this.codigoActividadField;
}
set {
this.codigoActividadField = value;
}
}
/// <remarks/>
public ulong NumeroConsecutivo {
get {
return this.numeroConsecutivoField;
}
set {
this.numeroConsecutivoField = value;
}
}
/// <remarks/>
public System.DateTime FechaEmision {
get {
return this.fechaEmisionField;
}
set {
this.fechaEmisionField = value;
}
}
/// <remarks/>
public FacturaElectronicaEmisor Emisor {
get {
return this.emisorField;
}
set {
this.emisorField = value;
}
}
/// <remarks/>
public FacturaElectronicaReceptor Receptor {
get {
return this.receptorField;
}
set {
this.receptorField = value;
}
}
/// <remarks/>
public byte CondicionVenta {
get {
return this.condicionVentaField;
}
set {
this.condicionVentaField = value;
}
}
/// <remarks/>
public byte PlazoCredito {
get {
return this.plazoCreditoField;
}
set {
this.plazoCreditoField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("MedioPago")]
public byte[] MedioPago {
get {
return this.medioPagoField;
}
set {
this.medioPagoField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("LineaDetalle", IsNullable = false)]
public FacturaElectronicaLineaDetalle[] DetalleServicio {
get {
return this.detalleServicioField;
}
set {
this.detalleServicioField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("OtrosCargos")]
public FacturaElectronicaOtrosCargos[] OtrosCargos {
get {
return this.otrosCargosField;
}
set {
this.otrosCargosField = value;
}
}
/// <remarks/>
public FacturaElectronicaResumenFactura ResumenFactura {
get {
return this.resumenFacturaField;
}
set {
this.resumenFacturaField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.w3.org/2000/09/xmldsig#")]
public Signature Signature {
get {
return this.signatureField;
}
set {
this.signatureField = value;
}
}
}
Example XML:
<FacturaElectronica xmlns="https://cdn.comprobanteselectronicos.go.cr/xml-schemas/v4.3/facturaElectronica" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<Clave>50601082000310133465800100001010000038444100147136</Clave>
<CodigoActividad>642005</CodigoActividad>
<NumeroConsecutivo>00100001010000038444</NumeroConsecutivo>
<FechaEmision>2020-08-01T19:47:58-06:00</FechaEmision>
<Emisor>
<Nombre>Callmyway NY</Nombre>
<Identificacion>
<Tipo>02</Tipo>
<Numero>3101334658</Numero>
</Identificacion>
<Ubicacion>
<Provincia>1</Provincia>
<Canton>01</Canton>
<Distrito>05</Distrito>
<Barrio>13</Barrio>
<OtrasSenas>COSTADO NORTE COLEGIO ABOGADOS FRENTE ENTRADA PRINCIPAL</OtrasSenas>
</Ubicacion>
<Telefono>
<CodigoPais>506</CodigoPais>
<NumTelefono>40004000</NumTelefono>
</Telefono>
<CorreoElectronico>facturacion#callmyway.com</CorreoElectronico>
</Emisor>
<Receptor>
<Nombre>GRUPO APLIX LATINOAMERICA SOCIEDAD ANONIMA</Nombre>
<Identificacion>
<Tipo>02</Tipo>
<Numero>3101753993</Numero>
</Identificacion>
</Receptor>
<CondicionVenta>01</CondicionVenta>
<PlazoCredito>0</PlazoCredito>
<MedioPago>04</MedioPago>
<MedioPago>02</MedioPago>
<DetalleServicio>
<LineaDetalle>
<NumeroLinea>1</NumeroLinea>
<CodigoComercial>
<Tipo>04</Tipo>
<Codigo>TR</Codigo>
</CodigoComercial>
<Cantidad>1</Cantidad>
<UnidadMedida>St</UnidadMedida>
<Detalle>Consumo Mensual Celular (2020-07)(6h23m9s)</Detalle>
<PrecioUnitario>839.99764</PrecioUnitario>
<MontoTotal>839.99764</MontoTotal>
<SubTotal>839.99764</SubTotal>
<BaseImponible>839.99764</BaseImponible>
<Impuesto>
<Codigo>01</Codigo>
<CodigoTarifa>08</CodigoTarifa>
<Tarifa>13.00</Tarifa>
<Monto>109.19969</Monto>
</Impuesto>
<ImpuestoNeto>109.19969</ImpuestoNeto>
<MontoTotalLinea>949.19733</MontoTotalLinea>
</LineaDetalle>
<LineaDetalle>
<NumeroLinea>2</NumeroLinea>
<CodigoComercial>
<Tipo>04</Tipo>
<Codigo>TR</Codigo>
</CodigoComercial>
<Cantidad>1</Cantidad>
<UnidadMedida>St</UnidadMedida>
<Detalle>Consumo Mensual Fijo (2020-07)(1h58m54s)</Detalle>
<PrecioUnitario>903.64052</PrecioUnitario>
<MontoTotal>903.64052</MontoTotal>
<SubTotal>903.64052</SubTotal>
<BaseImponible>903.64052</BaseImponible>
<Impuesto>
<Codigo>01</Codigo>
<CodigoTarifa>08</CodigoTarifa>
<Tarifa>13.00</Tarifa>
<Monto>117.47327</Monto>
</Impuesto>
<ImpuestoNeto>117.47327</ImpuestoNeto>
<MontoTotalLinea>1021.11379</MontoTotalLinea>
</LineaDetalle>
<LineaDetalle>
<NumeroLinea>3</NumeroLinea>
<CodigoComercial>
<Tipo>04</Tipo>
<Codigo>TR</Codigo>
</CodigoComercial>
<Cantidad>1</Cantidad>
<UnidadMedida>St</UnidadMedida>
<Detalle>Consumo Mensual internacional (2020-07)(2m47s)</Detalle>
<PrecioUnitario>297.81699</PrecioUnitario>
<MontoTotal>297.81699</MontoTotal>
<SubTotal>297.81699</SubTotal>
<BaseImponible>297.81699</BaseImponible>
<Impuesto>
<Codigo>01</Codigo>
<CodigoTarifa>08</CodigoTarifa>
<Tarifa>13.00</Tarifa>
<Monto>38.71621</Monto>
</Impuesto>
<ImpuestoNeto>38.71621</ImpuestoNeto>
<MontoTotalLinea>336.53320</MontoTotalLinea>
</LineaDetalle>
<LineaDetalle>
<NumeroLinea>4</NumeroLinea>
<CodigoComercial>
<Tipo>04</Tipo>
<Codigo>TR</Codigo>
</CodigoComercial>
<Cantidad>1</Cantidad>
<UnidadMedida>St</UnidadMedida>
<Detalle>Seleccion numero a la carta: 40015220</Detalle>
<PrecioUnitario>4357.29847</PrecioUnitario>
<MontoTotal>4357.29847</MontoTotal>
<SubTotal>4357.29847</SubTotal>
<BaseImponible>4357.29847</BaseImponible>
<Impuesto>
<Codigo>01</Codigo>
<CodigoTarifa>08</CodigoTarifa>
<Tarifa>13.00</Tarifa>
<Monto>566.44880</Monto>
</Impuesto>
<ImpuestoNeto>566.44880</ImpuestoNeto>
<MontoTotalLinea>4923.74727</MontoTotalLinea>
</LineaDetalle>
</DetalleServicio>
<OtrosCargos>
<TipoDocumento>02</TipoDocumento>
<Detalle>Timbre de la Cruz Roja</Detalle>
<MontoCargo>63.98754</MontoCargo>
</OtrosCargos>
<OtrosCargos>
<TipoDocumento>99</TipoDocumento>
<Detalle>Contribucion 911</Detalle>
<MontoCargo>47.99065</MontoCargo>
</OtrosCargos>
<ResumenFactura>
<CodigoTipoMoneda>
<CodigoMoneda>CRC</CodigoMoneda>
<TipoCambio>1</TipoCambio>
</CodigoTipoMoneda>
<TotalServGravados>6398.75362</TotalServGravados>
<TotalServExentos>0.00000</TotalServExentos>
<TotalServExonerado>0.00000</TotalServExonerado>
<TotalMercanciasGravadas>0.00000</TotalMercanciasGravadas>
<TotalMercanciasExentas>0.00000</TotalMercanciasExentas>
<TotalMercExonerada>0.00000</TotalMercExonerada>
<TotalGravado>6398.75362</TotalGravado>
<TotalExento>0.00000</TotalExento>
<TotalExonerado>0.00000</TotalExonerado>
<TotalVenta>6398.75362</TotalVenta>
<TotalDescuentos>0.00000</TotalDescuentos>
<TotalVentaNeta>6398.75362</TotalVentaNeta>
<TotalImpuesto>831.83797</TotalImpuesto>
<TotalOtrosCargos>111.97819</TotalOtrosCargos>
<TotalComprobante>7342.56978</TotalComprobante>
</ResumenFactura>
</FacturaElectronica>
I tried to create the billing class from a larger xml file, but it didn't work due to missing nodes. Since the class doesn't match the XML structure, it doesn't work with all files except the one I shared with you. I expect to open XML files of similar structure
Solved
I had it with using the Visual Studio Auto Generated code. After a deep research I found the tool XSD.exe. With this tool I found out how to create a class from a XSD file. I needed to download linked schemas in order for it to work:
First, I opened Developer Command Prompt for VS 2019, then I used CD commands to reach the files path, after that, i used the command:
xsd /c {random_xsd_file}.xsd {another_rnd_xsd_file}.xsd
With that, i created a .cs file containing all the classes needed. (If someone have any question feel free to ask, I spent lots of time researching this :p).

SOAP web service reference to generic class returns nullexception

this is my debut on stackoverflow as a writer. I'm stacked...
I have Windows Forms Application. I added ServiceReference to .wsdl web service. Everything works good but I have problem with initialize fields from generic class.
This class looks that below:
public partial class setHuntingGroupRequest : object, System.ComponentModel.INotifyPropertyChanged {
private string fwSessionIdField;
private string pbxNameField;
private AlcHuntingGroup huntingGroupField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Order=0)]
public string fwSessionId {
get {
return this.fwSessionIdField;
}
set {
this.fwSessionIdField = value;
this.RaisePropertyChanged("fwSessionId");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Order=1)]
public string pbxName {
get {
return this.pbxNameField;
}
set {
this.pbxNameField = value;
this.RaisePropertyChanged("pbxName");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Order=2)]
public AlcHuntingGroup huntingGroup {
get {
return this.huntingGroupField;
}
set {
this.huntingGroupField = value;
this.RaisePropertyChanged("huntingGroup");
}
}
So i have fwSessionId, pbxName and nested AlcHuntingGroup which looks:
public partial class AlcHuntingGroup : object, System.ComponentModel.INotifyPropertyChanged {
private string directoryNumberField;
private string directoryNameField;
private AlcHuntingGroupSearchType searchTypeField;
private string[] membersField;
private bool unavailableAuthorizedField;
private bool releaseAfterTimerField;
private string overflowDirectoryNumberField;
private int entityField;
(...)
How my code works:
private void btnDodajnrdohg_Click(object sender, EventArgs e)
{
SoapDemo.ServiceReference1.AlcPbxManagementPortTypeClient soap = new
SoapDemo.ServiceReference1.AlcPbxManagementPortTypeClient();
setHuntingGroupRequest request = new setHuntingGroupRequest();
setHuntingGroupResponse response = new setHuntingGroupResponse();
request.fwSessionId = session_id;
request.pbxName = "demooxemai42";
try
{
response = soap.setHuntingGroup(request);
this.output.Text = response.resultCode.ToString();
}
catch (Exception error)
{
this.output.Text = "Error in request: " + error + "\n";
}
}
In this above example I insert to request two fields. Unfortunetaly I must also insert all fields from AlcHuntingGroup class (huntingGroup is reference to this class). I tried this:
request.fwSessionId = session_id;
request.pbxName = "demooxemain2";
request.huntingGroup.directoryName = "Directory Name";
request.huntingGroup.directoryNumber = "1001";
request.huntingGroup.entity = 1;
//etc
Intellisense properly see this fields, but when I'm start debugging this code it's return me an error in line where I have request.huntingGroup.directoryName = "Directory Name";
System.NullReferenceException: object reference not set to an instance of an object
SoapDemo.ServiceReference1.setHuntingGroupRequest.huntingGroup.get returned null.
How can I protect from get null value from huntingGroup?
request.huntingGroup.directoryName = "Directory Name";
on your code this part
request.huntingGroup
calls getter of property. You need to initialize it first or improve getter by something like this:
get {
return this.huntingGroupField ?? (this.huntingGroupField = new AlcHuntingGroup());
}
This approach called "lazy initialization" - huntingGroupField will be initialized automatically when you try to access huntingGroup property first time.

Understanding the error "the name does not exists in the current context"

I am using C#. I get an error:
The name 'DateAndTime','DateInterval' 'FirstDayOfWeek','FirstWeekOfYear', does not exist in the current context
which I don't understand. I tried a lot of solutions on it but it is not working.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.IO;
using Microsoft.VisualBasic;
using System.Windows.Forms;
namespace SoftwareLocker
{
// Activate Property
public class TrialMaker
{
#region -> Private Variables
private string _BaseString;
private string _Password;
private string _SoftName;
private string _RegFilePath;
private string _HideFilePath;
private int _DefDays;
private int _Runed;
private string _Text;
private string _Identifier;
#endregion
#region -> Constructor
/// <summary>
/// Make new TrialMaker class to make software trial
/// </summary>
/// <param name="SoftwareName">Name of software to make trial</param>
/// <param name="RegFilePath">File path to save password(enrypted)</param>
/// <param name="HideFilePath">file path for saving hidden information</param>
/// <param name="Text">A text for contacting to you</param>
/// <param name="TrialDays">Default period days</param>
/// <param name="TrialRunTimes">How many times user can run as trial</param>
/// <param name="Identifier">3 Digit string as your identifier to make password</param>
public TrialMaker(string SoftwareName,
string RegFilePath, string HideFilePath,
string Text, int TrialDays, int TrialRunTimes,
string Identifier)
{
_SoftName = SoftwareName;
_Identifier = Identifier;
SetDefaults();
_DefDays = TrialDays;
_Runed = TrialRunTimes;
_RegFilePath = RegFilePath;
_HideFilePath = HideFilePath;
_Text = Text;
}
private void SetDefaults()
{
SystemInfo.UseBaseBoardManufacturer = false;
SystemInfo.UseBaseBoardProduct = true;
SystemInfo.UseBiosManufacturer = false;
SystemInfo.UseBiosVersion = true;
SystemInfo.UseDiskDriveSignature = true;
SystemInfo.UsePhysicalMediaSerialNumber = false;
SystemInfo.UseProcessorID = true;
SystemInfo.UseVideoControllerCaption = false;
SystemInfo.UseWindowsSerialNumber = false;
MakeBaseString();
MakePassword();
}
#endregion
// Make base string (Computer ID)
private void MakeBaseString()
{
_BaseString = Encryption.Boring(Encryption.InverseByBase(SystemInfo.GetSystemInfo(_SoftName), 10));
}
private void MakePassword()
{
_Password = Encryption.MakePassword(_BaseString, _Identifier);
}
/// <summary>
/// Show registering dialog to user
/// </summary>
/// <returns>Type of running</returns>
public RunTypes ShowDialog()
{
// check if registered before
if (CheckRegister() == true)
return RunTypes.Full;
frmDialog PassDialog = new frmDialog(_BaseString, _Password, DaysToEnd(), _Runed, _Text);
MakeHideFile();
DialogResult DR = PassDialog.ShowDialog();
if (DR == System.Windows.Forms.DialogResult.OK)
{
MakeRegFile();
return RunTypes.Full;
}
else if (DR == DialogResult.Retry)
return RunTypes.Trial;
else
return RunTypes.Expired;
}
// save password to Registration file for next time usage
private void MakeRegFile()
{
FileReadWrite.WriteFile(_RegFilePath, _Password);
}
// Control Registeration file for password
// if password saved correctly return true else false
private bool CheckRegister()
{
string Password = FileReadWrite.ReadFile(_RegFilePath);
if (_Password == Password)
return true;
else
return false;
}
// from hidden file
// indicate how many days can user use program
// if the file does not exists, make it
private int DaysToEnd()
{
FileInfo hf = new FileInfo(_HideFilePath);
if (hf.Exists == false)
{
MakeHideFile();
return _DefDays;
}
return CheckHideFile();
}
// store hidden information to hidden file
// Date,DaysToEnd,HowManyTimesRuned,BaseString(ComputerID)
private void MakeHideFile()
{
string HideInfo;
HideInfo = DateTime.Now.Ticks + ";";
HideInfo += _DefDays + ";" + _Runed + ";" + _BaseString;
FileReadWrite.WriteFile(_HideFilePath, HideInfo);
}
// Get Data from hidden file if exists
private int CheckHideFile()
{
string[] HideInfo;
HideInfo = FileReadWrite.ReadFile(_HideFilePath).Split(';');
long DiffDays;
int DaysToEnd;
if (_BaseString == HideInfo[3])
{
DaysToEnd = Convert.ToInt32(HideInfo[1]);
if (DaysToEnd <= 0)
{
_Runed = 0;
_DefDays = 0;
return 0;
}
DateTime dt = new DateTime(Convert.ToInt64(HideInfo[0]));
DiffDays = DateAndTime.DateDiff(DateInterval.Day,
dt.Date, DateTime.Now.Date,
FirstDayOfWeek.Saturday,
FirstWeekOfYear.FirstFullWeek);
DaysToEnd = Convert.ToInt32(HideInfo[1]);
_Runed = Convert.ToInt32(HideInfo[2]);
_Runed -= 1;
DiffDays = Math.Abs(DiffDays);
_DefDays = DaysToEnd - Convert.ToInt32(DiffDays);
}
return _DefDays;
}
public enum RunTypes
{
Trial = 0,
Full,
Expired,
UnKnown
}
#region -> Properties
/// <summary>
/// Indicate File path for storing password
/// </summary>
public string RegFilePath
{
get
{
return _RegFilePath;
}
set
{
_RegFilePath = value;
}
}
/// <summary>
/// Indicate file path for storing hidden information
/// </summary>
public string HideFilePath
{
get
{
return _HideFilePath;
}
set
{
_HideFilePath = value;
}
}
/// <summary>
/// Get default number of days for trial period
/// </summary>
public int TrialPeriodDays
{
get
{
return _DefDays;
}
}
/// <summary>
/// Get or Set TripleDES key for encrypting files to save
/// </summary>
public byte[] TripleDESKey
{
get
{
return FileReadWrite.key;
}
set
{
FileReadWrite.key = value;
}
}
#endregion
#region -> Usage Properties
public bool UseProcessorID
{
get
{
return SystemInfo.UseProcessorID;
}
set
{
SystemInfo.UseProcessorID = value;
}
}
public bool UseBaseBoardProduct
{
get
{
return SystemInfo.UseBaseBoardProduct;
}
set
{
SystemInfo.UseBaseBoardProduct = value;
}
}
public bool UseBaseBoardManufacturer
{
get
{
return SystemInfo.UseBiosManufacturer;
}
set
{
SystemInfo.UseBiosManufacturer = value;
}
}
public bool UseDiskDriveSignature
{
get
{
return SystemInfo.UseDiskDriveSignature;
}
set
{
SystemInfo.UseDiskDriveSignature = value;
}
}
public bool UseVideoControllerCaption
{
get
{
return SystemInfo.UseVideoControllerCaption;
}
set
{
SystemInfo.UseVideoControllerCaption = value;
}
}
public bool UsePhysicalMediaSerialNumber
{
get
{
return SystemInfo.UsePhysicalMediaSerialNumber;
}
set
{
SystemInfo.UsePhysicalMediaSerialNumber = value;
}
}
public bool UseBiosVersion
{
get
{
return SystemInfo.UseBiosVersion;
}
set
{
SystemInfo.UseBiosVersion = value;
}
}
public bool UseBiosManufacturer
{
get
{
return SystemInfo.UseBiosManufacturer;
}
set
{
SystemInfo.UseBiosManufacturer = value;
}
}
public bool UseWindowsSerialNumber
{
get
{
return SystemInfo.UseWindowsSerialNumber;
}
set
{
SystemInfo.UseWindowsSerialNumber = value;
}
}
#endregion
}
}
that problem will work on Viaual basic 2005 it is not working in vb2015 if, we do so in 2015 some libraries are missing that pblm raises

I don't see any pictures in my RSS

I have problem. I programming Windows Phone 8.0 application and i don't see anything pictures in my app. Probably error is in regex, because in debug regImg don't have any matches
Class MainPage.xaml.cs
string strURL = "https://news.google.com/news? cf=all&ned=pl_pl&hl=pl&topic=b&output=rss"; // URL of RssFeeds.
and class ImageFromRssText.cs
public class ImageFromRssText : IValueConverter
{
// Get images from each SyndicationItem.
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) return null;
List<ImageItem> listUri = GetHtmlImageUrlList(value.ToString());
return listUri;
}
/// <summary>
/// Get the URL of the all pictures from the HTML.
/// </summary>
/// <param name="sHtmlText">HTML code</param>
/// <returns>URL list of the all pictures</returns>
public static List<ImageItem> GetHtmlImageUrlList(string sHtmlText)
{
// The definition of a regular expression to match img tag.
Regex regImg = new Regex(#"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
// The search for a matching string.
MatchCollection matches = regImg.Matches(sHtmlText);
int i = 0;
List<ImageItem> imgUrlList = new List<ImageItem>();
// Get a list of matches
foreach (Match match in matches)
{
imgUrlList.Add(new ImageItem("img" + i, match.Groups["imgUrl"].Value));
i++;
}
return imgUrlList;
}
Ok. I wrote a little bit in a different way in second project(yesterday I wrote a project of a new). Although the problem is the same, then it does not load picture. Function HasImage always return false(Although when picture exists) and variabe Image is null(rest of variables are OK)
public class FeedItemViewModel : System.ComponentModel.INotifyPropertyChanged
{
// Declaration - Title, Image, Lead, Url
private string _title;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
OnPropertyChanged("Title");
}
}
// All from RSS (Image and lead)
private string _lead;
public string Lead
{
get
{
return _lead;
}
set
{
_lead = value;
// Load picture
try
{
if (TryParseImageUrl(_lead, out _imageUrl))
_imageUrl = _imageUrl.Replace("//", "http://");
}
catch { }
OnPropertyChanged("Lead");
}
}
private string _imageUrl;
public Uri Image
{
get
{
if (HasImage)
return new Uri(_imageUrl, UriKind.RelativeOrAbsolute);
return null;
}
}
// Check if picture exists
public bool HasImage
{
get
{
return (!string.IsNullOrEmpty(_imageUrl) && Uri.IsWellFormedUriString(_imageUrl, UriKind.RelativeOrAbsolute));
}
}
// Download url news
private string _url;
public string Url
{
get
{
return _url;
}
set
{
_url = value;
OnPropertyChanged("Url");
}
}
public void OnOpenUrl()
{
var wb = new Microsoft.Phone.Tasks.WebBrowserTask();
wb.Uri = new Uri(_url);
wb.Show();
}
// 3 method parse image
private static bool TryParseImageUrl(string description, out string result)
{
string str = ParseAnyImageInTheDescription(description);
result = str;
return (!string.IsNullOrEmpty(str) && Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute));
}
private static string ParseAnyImageInTheDescription(string item)
{
if (item == null) { return null; }
return ParseImageUrlFromHtml(item);
}
private static string ParseImageUrlFromHtml(string html)
{
Match match = new Regex("src=(?:\\\"|\\')?(?<imgSrc>[^>]*[^/].(?:jpg|png|jpeg))(?:\\\"|\\')?").Match(html);
if ((match.Success && (match.Groups.Count > 1)) && (match.Groups[1].Captures.Count > 0))
{
return match.Groups[1].Captures[0].Value;
}
return null;
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}

itunes listening to

within windows live messenger, it is possible to share the song you are currently listening to. what would i need to do to get this working within c# like libarys etc cannot find the correct documentation on google.
You'll need to use the iTunes SDK to interact with iTunes from .NET. So there's your Google search term. :)
Here's a start:
http://blogs.msdn.com/b/noahc/archive/2006/07/06/automating-itunes-with-c-in-net.aspx
http://blogs.msdn.com/b/dancre/archive/2004/05/08/128645.aspx
Here is a script for LinqPad in C# which does as requested. (see LinqPad.com)
Bonus! Artwork view.
It looks like this:
<Query Kind="Program">
<Namespace>iTunesLib</Namespace>
<Namespace>System.Security.Cryptography</Namespace>
</Query>
void Main()
{
var track = new iTunesApp().CurrentTrack;
if (track == null)
"nothing playing".Dump();
else
new Viewer(track,true).Dump();
}
public class Viewer
{
const string PREFIX = "itlps-";
private IITFileOrCDTrack store;
private bool materialize;
public string album { get { return store.Album; } }
public string band { get { return store.Artist; } }
public string song { get { return store.Name; } }
public string desc { get { return store.Description; } }
public int? artCnt { get {
if (store.Artwork == null) return null;
else return store.Artwork.Count; }
}
public IEnumerable<ImageViewer> art { get {
if (materialize)
{
foreach(var artT in store.Artwork)
{
var art = artT as IITArtwork;
string ext = ".tmp";
switch(art.Format)
{
case ITArtworkFormat.ITArtworkFormatBMP:
ext = ".BMP";
break;
case ITArtworkFormat.ITArtworkFormatJPEG:
ext = ".JPG";
break;
case ITArtworkFormat.ITArtworkFormatPNG:
ext = ".PNG";
break;
}
string path = Path.Combine(Path.GetTempPath(),PREFIX+Path.GetRandomFileName()+ext);
art.SaveArtworkToFile(path);
yield return new ImageViewer(path);
}
}
yield break; }
}
public Viewer(IITFileOrCDTrack t,bool materializeArt = false)
{
store = t;
materialize = materializeArt;
}
public Viewer(IITTrack t,bool materializeArt = false)
{
store = t as IITFileOrCDTrack;
materialize = materializeArt;
}
}
public class ImageViewer
{
public string hash { get { return _hash.Value; } }
static private string _path { get; set; }
public object image { get { return _image.Value; } }
static private SHA1Managed sha = new SHA1Managed();
private Lazy<object> _image = new Lazy<object>(() => {return Util.Image(_path);});
private Lazy<string> _hash = new Lazy<string>(() =>
{
string hash = string.Empty;
using (FileStream stream = File.OpenRead(_path))
{
byte [] checksum = sha.ComputeHash(stream);
hash = BitConverter.ToString(checksum).Replace("-", string.Empty);
}
return hash;
});
public ImageViewer(string path)
{
_path = path;
}
}
last i checked this functionality is included out of the box all you need is to have itunes and windows live messenger installed and activate "what im listening to" and it shows this in your messenger status. if you are looking to create a bot that messages this out to a contact that is a different story tho that you will need to write a script for

Categories