How to read value of an attribute defined in app.config? - c#

I have a app.config file that in the form of :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<endpoint address="http://something.com"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IFileTransfer"
contract="ABC" name="XXX" />
<endpoint address="http://something2.com"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IFileTransfer"
contract="ABC2" name="YYY" />
</client>
</system.serviceModel>
</configuration>
I want to read the value at attribute "address" of node endpoint which has the name="XXX". Please show me how to do it!
(Continue belowing disscussing with marc_s. Sorry to put the text here since comment do not allow to format codes )
#marc_s: I use the below codes to read the above file but it shows that the clientSection.Endpoints has 0 members (Count=0). Please help!
public MainWindow()
{
var exeFile = Environment.GetCommandLineArgs()[0];
var configFile = String.Format("{0}.config", exeFile);
var config = ConfigurationManager.OpenExeConfiguration(configFile);
var wcfSection = ServiceModelSectionGroup.GetSectionGroup(config);
var clientSection = wcfSection.Client;
foreach (ChannelEndpointElement endpointElement in clientSection.Endpoints)
{
if (endpointElement.Name == "XXX")
{
var addr = endpointElement.Address.ToString();
}
}
}

You really don't need to - the WCF runtime will do all of that for you.
If you really must - for whatever reason - you can do this:
using System.Configuration;
using System.ServiceModel.Configuration;
ClientSection clientSettings = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
string address = null;
foreach(ChannelEndpointElement endpoint in clientSettings.Endpoints)
{
if(endpoint.Name == "XXX")
{
address = endpoint.Address.ToString();
break;
}
}

You can use the ServiceModelSectionGroup (System.ServiceModel.Configuration) to access the configuration:
var config = ConfigurationManager.GetSection("system.serviceModel") as ServiceModelSectionGroup;
foreach (ChannelEndpointElement endpoint in config.Client.Endpoints)
{
Uri address = endpoint.Address;
// Do something here
}
Hope that helps.

var config = ConfigurationManager.OpenExeConfiguration("MyApp.exe.config");
var wcfSection = ServiceModelSectionGroup.GetSectionGroup(config);
var clientSection = wcfSection.Client;
foreach(ChannelEndpointElement endpointElement in clientSection.Endpoints) {
if(endpointElement.Name == "XXX") {
return endpointElement.Address;
}
}

Related

An error occurred while receiving the HTTP response WCF

I have a Windows app connecting to a WCF service that uses Entity Framework and is hosted in IIS. I get this error message when I try to return result of method in WCF service to my windows app:
An error occurred while receiving the HTTP response to http://localhost/BuyAndRechargeWcfService/BuyAndRechargeService.svc. > This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
Here is my web.config file of the WCF service:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="DatabaseName" value="Recharge System"/>
<add key="ServerName" value="SAA"/>
<add key="UserId" value="sa"/>
<add key="Password" value="**"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
</system.webServer>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Here is exe.config file in Windows app:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="DatabaseName" value="Recharge System"/>
<add key="ServerName" value="SAA"/>
<add key="UserId" value="sa"/>
<add key="Password" value="**"/>
<add key="DataSourceType" value="wcf"/>
</appSettings>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IBuyAndRechargeService" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost/BuyAndRechargeWcfService/BuyAndRechargeService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IBuyAndRechargeService"
contract="BuyAndRechargeService.IBuyAndRechargeService" name="BasicHttpBinding_IBuyAndRechargeService" />
</client>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Here is service code:
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using EntityFarmework;
using Sedco.SelfService.Kiosk.SharedProject;
namespace BuyAndRechargeWcfService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "BuyAndRechargeService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select BuyAndRechargeService.svc or BuyAndRechargeService.svc.cs at the Solution Explorer and start debugging.
public class BuyAndRechargeService : IBuyAndRechargeService
{
private readonly BuyAndRechargeSystemModel _dataBaseEntities = new BuyAndRechargeSystemModel(new DatabaseConfiguration().GetWebConfiguration());
public dynamic HandleCustomer(string action, Dictionary<string, string> customerData)
{
dynamic result = null;
switch (action)
{
case "checkExistingPhoneNumber":
{
result= CheckExistingPhoneNumber(customerData);
break;
}
case "getCustomers":
{
result= GetCustomers();
break;
}
case "getCustomerInformation":
{
result= GetCustomerInformation(customerData);
break;
}
case "rechargeBalance":
{
result= RechargeBalance(customerData);
break;
}
case "getFilteredCustomers":
{
result= GetFilteredCustomers(customerData);
break;
}
case "deleteCustomers":
{
result= DeleteCustomers(customerData);
break;
}
case "checkIfNoCustomers":
{
result= CheckIfNoCustomers();
break;
}
case "addCustomer":
{
result= AddCustomer(customerData);
break;
}
case "getExpireDate":
{
result= GetExpireDate(customerData);
break;
}
case "editCustomer":
{
result= EditCustomer(customerData);
break;
}
default:
return false;
}
return result;
}
public dynamic HandlePackages(string action, Dictionary<string, string> packageInfo)
{
dynamic result = null;
switch (action)
{
case "getPackagesList":
result = _dataBaseEntities.Packages.Where(package => package.Type.Equals(packageInfo["packageType"]))
.Select(package => package.Name).ToList();
break;
case "addPackage":
try
{
Packages package = new Packages();
package.Name = packageInfo["packageName"];
package.Type = packageInfo["packageType"];
package.price = Int32.Parse(packageInfo["packagePrice"]);
_dataBaseEntities.Packages.Add(package);
_dataBaseEntities.SaveChanges();
result = true;
}
catch
{
result = false;
}
break;
case "getPackageTypeFromName":
result = _dataBaseEntities.Packages.Where(package => package.Name.Equals(packageInfo["packageName"]))
.Select(package => package.Type).FirstOrDefault();
break;
case "checkExistingPackages":
int packages = _dataBaseEntities.Packages.Where(package => package.Name == packageInfo["packageName"])
.Select(package => package.Name).Count();
result = packages != 0;
break;
}
return result;
}
private bool EditCustomer(Dictionary<string, string> customerData)
{
bool isEdited = false;
Customers customer =
_dataBaseEntities.Customers.FirstOrDefault(customerPhone =>
customerPhone.PhoneNumber.Equals(customerData["phoneNumber"]));
if (customer != null)
{
int packageId = _dataBaseEntities.Packages.Where(package => package.Name.Equals(customerData["packageName"]))
.Select(package => package.ID).FirstOrDefault();
customer.Name = customerData["editCustomerName"];
customer.BirthDate = customerData["editCustomerBirthDate"];
customer.PackageID = packageId;
_dataBaseEntities.SaveChanges();
isEdited = true;
}
else
{
isEdited = false;
}
return isEdited;
}
private DateTime GetExpireDate(Dictionary<string, string> customerData)
{
DateTime? expireDate = _dataBaseEntities.Customers
.Where(customer => customer.PhoneNumber.Equals(customerData["phoneNumber"]))
.Select(customer => customer.ExpireDate)
.FirstOrDefault();
return (DateTime)expireDate;
}
private bool AddCustomer(Dictionary<string, string> customerData)
{
bool result = false;
try
{
Customers customer = new Customers();
int packageId = _dataBaseEntities.Packages.Where(package => package.Name.Equals(customerData["packageName"]))
.Select(package => package.ID).SingleOrDefault();
int packagePrice = _dataBaseEntities.Packages.Where(package => package.Name.Equals(customerData["packageName"]))
.Select(package => package.price).FirstOrDefault();
string expireDateADateTime = DateTime.Now.AddMonths(3).ToString("yyyy-MM-dd HH:mm:ss");
DateTime expireDate = DateTime.ParseExact(expireDateADateTime, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture);
customer.Name = customerData["customerName"];
customer.PhoneNumber = customerData["phoneNumber"];
customer.BirthDate = customerData["customerBirthDate"];
customer.PackageID = packageId;
customer.ExpireDate = expireDate;
customer.Balance = packagePrice;
_dataBaseEntities.Customers.Add(customer);
_dataBaseEntities.SaveChanges();
result = true;
}
catch (DbEntityValidationException e)
{
e.EntityValidationErrors.SelectMany(error => error.ValidationErrors).ToList().ForEach(
item => Console.WriteLine("{0} - {1}", item.PropertyName, item.ErrorMessage));
result = false;
}
catch (Exception ex)
{
result = false;
}
return result;
}
private bool CheckIfNoCustomers()
{
bool isNoCustomer = false;
int countOfCustomers = _dataBaseEntities.Customers.Count();
if (countOfCustomers == 0)
{
isNoCustomer = true;
}
else
{
isNoCustomer = false;
}
return isNoCustomer;
}
private bool DeleteCustomers(Dictionary<string, string> customerData)
{
bool isDeleted = true;
bool result = false;
List<Customers> deleteQuery = new List<Customers>();
foreach (string phoneNumber in customerData["phoneNumber"].Split(','))
{
Customers customerRow =
_dataBaseEntities.Customers.Single(customer => customer.PhoneNumber.Equals(phoneNumber));
deleteQuery.Add(customerRow);
if (customerRow != null)
{
isDeleted = true && isDeleted;
}
else
{
isDeleted = false && isDeleted;
break;
}
}
foreach (Customers delete in deleteQuery)
{
if (isDeleted)
{
_dataBaseEntities.Customers.Remove(delete);
_dataBaseEntities.SaveChanges();
result = true;
}
else
{
result = false;
}
}
return result;
}
private List<Customer> GetFilteredCustomers(Dictionary<string, string> customerData)
{
return _dataBaseEntities.Customers
.Where(customers =>
customers.Name.Contains(customerData["Search"]) ||
customers.PhoneNumber.Contains(customerData["Search"])).Select(customer => new Customer
{
CustomerName = customer.Name,
CustomerPhoneNumber = customer.PhoneNumber,
CustomerBirthdate = customer.BirthDate,
CustomerPackageName = customer.Packages.Name,
CustomerBalance = Convert.ToDecimal(customer.Balance)
}).ToList();
}
private string RechargeBalance(Dictionary<string, string> customerData)
{
Customers customerBalance = _dataBaseEntities.Customers.Single(customerPhoneNumber =>
customerPhoneNumber.PhoneNumber.Equals(customerData["PhoneNumber"]));
customerBalance.Balance = customerBalance.Balance + Convert.ToDecimal(customerData["Amount"]);
IFormatProvider culture = System.Globalization.CultureInfo.CurrentCulture;
customerBalance.ExpireDate = DateTime.ParseExact(DateTime.Now.AddMonths(1).ToString("dd-MM-yyyy"),
"dd-MM-yyyy", culture);
_dataBaseEntities.SaveChanges();
return customerBalance.Balance.ToString();
}
private Customer GetCustomerInformation(Dictionary<string, string> customerData)
{
return _dataBaseEntities.Customers
.Where(customers => customers.PhoneNumber.Equals(customerData["PhoneNumber"])).Select(
customer => new Customer
{
CustomerName = customer.Name,
CustomerPhoneNumber = customer.PhoneNumber,
CustomerBirthdate = customer.BirthDate,
CustomerPackageName = customer.Packages.Name,
CustomerBalance = (decimal)customer.Balance
}).Single();
}
private XmlNode[] GetCustomers()
{
var customers = _dataBaseEntities.Customers.Select(customerInfo => new Customer
{
CustomerName = customerInfo.Name,
CustomerPhoneNumber = customerInfo.PhoneNumber,
CustomerBirthdate = customerInfo.BirthDate,
CustomerPackageName = customerInfo.Packages.Name,
CustomerBalance = (decimal)customerInfo.Balance
}).ToList();
//Convert the List<Customer> object to an XmlNode[] object
XmlSerializer serializer = new XmlSerializer(typeof(List<Customer>));
using (StringWriter stringWriter = new StringWriter())
{
serializer.Serialize(stringWriter, customers);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(stringWriter.ToString());
return xmlDoc.ChildNodes.Cast<XmlNode>().ToArray();
}
}
private bool CheckExistingPhoneNumber(Dictionary<string, string> customerData)
{
return _dataBaseEntities.Customers.Count(
number => number.PhoneNumber == customerData["PhoneNumber"]) != 0;
}
}
}
When I try to debug the code I reach the return value of HandleCustomer method in WCF service and then I can't complete debugging (can't move to other statement the arrows is been disabled).
Please tell me if you want to provide you in any other parts of code
If possible, please check whether there is a record of 0 in the data found in the database.
When read in a program, it is converted to the corresponding enumeration type (enum), which does not define the enumeration value corresponding to 0. In this case, the conversion to an enumeration type does not throw an exception, and the value of the property remains 0 after the conversion. But when it is returned to the WCF client, the above exception is thrown.
The solution is to define the enumerated value corresponding to 0 in the enumerated type.

How to Solve DTD is prohibited in this xml document in WCF while connecting with Xamarin forms

I'm trying to connect my WCF service in Xamarine Forms, but in runtime I am getting this error
For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
LoginWCFService.svc.cs
public class LoginWCFService : ILoginWCFService
{
public string LoginUserDetails(UserDetails userInfo)
{
string result = string.Empty;
bool res = false;
if (userInfo.uName!="" && userInfo.pWord != "" || userInfo.uName != null && userInfo.pWord != null)
{
result = "Login Successfull...";
}
else
{
res = false;
result = "Empty username or password";
}
return result.ToString();
}
}
ILoginWCFService.cs
[ServiceContract]
public interface ILoginWCFService
{
[OperationContract]
string LoginUserDetails(UserDetails UserInfo);
}
public class UserDetails
{
string UserName = string.Empty;
string Password = string.Empty;
[DataMember]
public string uName
{
get { return UserName; }
set { UserName = value; }
}
[DataMember]
public string pWord
{
get { return Password; }
set { Password = value; }
}
}
web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ILoginWCFService" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://wcfapi.local/LoginWCFService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ILoginWCFService"
contract="WcfService_Omss.ILoginWCFService" name="BasicHttpBinding_ILoginWCFService" />
</client>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Consuming WCF in Xamarine Form
LoginPage.xaml.cs
WCFServiceReference.LoginWCFServiceClient client = new LoginWCFServiceClient();
client.Open();
UserDetails user = new UserDetails();
user.uName = Uname.Text.ToString();
user.pWord = Pass.Text.ToString();
var res = client.LoginUserDetails(user); //Getting error here
if (res == "Login Successfull...")
await DisplayAlert("Message", "Login Successfull...", "Cancel");
else
await DisplayAlert("Message", "Login failed...", "Cancel");
client.Close();
Can anyone please tell me where I have to do changes to resolve this error?
This error has nothing to do with the wcf service. As the message says, set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings to the XmlReader.Create method. You can refer to the code below.
https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings.dtdprocessing?view=net-6.0
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class Sample {
public static void Main() {
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.ValidationType = ValidationType.DTD;
settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("itemDTD.xml", settings);
// Parse the file.
while (reader.Read());
}
// Display any validation errors.
private static void ValidationCallBack(object sender, ValidationEventArgs e) {
Console.WriteLine("Validation Error: {0}", e.Message);
}
}

Return JSON instead of XML web service

I'm wanting my web service to return JSON not XML, currently it's returning JSON wrapped in XML. View the source of my URL http://soulappvm.cloudapp.net/SAService/Service.svc/userlist produces the following...
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">[{"Name":"Daniel1user","Password":"40d5e24c5c906103a980ec7c69c100c5","Address":"123 st"},{"Name":"Daniel2user","Password":"90a1587cbe37d4a2a128ce758f338587","Address":"1234 st"},{"Name":"Daniel3user","Password":"f97c27c65d3af0d18657cbae16f9d57e","Address":"ccc"},{"Name":"user1user","Password":"def907bec025cd03bf738c3612bd7926","Address":"ds"},{"Name":"user2user","Password":"0fa04e1c4a5720195b106df9e746a72b","Address":"ff"}]</string>
Is there simple way to get it to just return JSON? I have tried ResponseFormat = WebMessageFormat.Json but that did not work.
IService
namespace SoulInfoService
{
[ServiceContract(SessionMode = SessionMode.Allowed, Namespace = "http://mmmkay95989.wix.com/bb2soulinfo")]
public interface IService
{
[OperationContract]
[WebGet(UriTemplate = "id")]
//[AspNetCacheProfile("CacheFor1200Seconds")]
string ServiceID();
[OperationContract]
[WebGet(UriTemplate = "version")]
//[AspNetCacheProfile("CacheFor1200Seconds")]
string Version();
[OperationContract]
[WebGet(UriTemplate = "userlist", ResponseFormat = WebMessageFormat.Json)]
[AspNetCacheProfile("CacheFor1200Seconds")]
string UserList();
[OperationContract]
[WebGet(UriTemplate = "usersearch?term={term}")]
User[] UserSearch(string term);
[OperationContract]
[WebGet(UriTemplate = "soulimg?id={id}")]
Stream SoulImage(string id);
[OperationContract]
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
void GetOptions();
} // interface
}
Service
namespace SoulInfoService
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
public Service()
{
serviceID = Guid.NewGuid();
} // Service
public string ServiceID()
{
string rval = "";
rval = serviceID.ToString();
return rval;
} // ServiceID
public string Version()
{
return "1.0.0";
} // Version
public void GetOptions()
{
} // GetOptions
public string UserList()
{
User[] rval = null;
using (var sqlCommand = new SQLiteCommand("SELECT * FROM Users"))
{
rval = GetUsers(sqlCommand);
}
return JsonConvert.SerializeObject(rval);
//return rval;
} // UserList
public User[] UserSearch(string term)
{
User[] rval = null;
#if SANITY_CHECK
term = Sanitize(term);
#endif
string sqlString = String.Format("SELECT * FROM Users WHERE username LIKE '%{0}%'", term);
using (var sqlCommand = new SQLiteCommand(sqlString))
{
rval = GetUsers(sqlCommand);
}
for (int i = 0; i < rval.Length; i++)
{
System.Diagnostics.Debug.WriteLine("value: " + rval[i].Name);
}
return rval;
} // UserSearch
public Stream SoulImage(string id)
{
string categoryFolder = "/Souls/";
return GetImage(id, categoryFolder);
} //SoulImage
private Stream GetImage(string id, string categoryFolder)
{
string mimeType = "image/jpeg";
string fileExtension = "jpg";
ConfigReader config = new ConfigReader();
string dataRoot = config.GetString(CONFIG_DATA_ROOT, #"C:/");
string img = dataRoot + "/Images/" + categoryFolder + "/" + Path.ChangeExtension(id, fileExtension);
MemoryStream ms = null;
if (!File.Exists(img))
{
mimeType = "image/gif";
fileExtension = "gif";
img = dataRoot + "/Images/" + categoryFolder + "/" + Path.ChangeExtension(id, fileExtension);
if (!File.Exists(img))
{
mimeType = "image/png";
fileExtension = "png";
img = dataRoot + "/Images/" + categoryFolder + "/" + Path.ChangeExtension(id, fileExtension);
if (!File.Exists(img))
{
img = dataRoot + "/Images/Default.png";
}
}
}
ms = new MemoryStream(File.ReadAllBytes(img));
WebOperationContext.Current.OutgoingResponse.ContentType = mimeType;
return ms;
} // GetImage
private User[] GetUsers(SQLiteCommand command)
{
var list = new List<User>();
try
{
using (SQLiteConnection dbConnection = OpenDBConnection())
{
command.Connection = dbConnection;
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var b = new User()
{
//Id = reader["TextId"].ToString(),
Name = reader["Username"].ToString(),
Password = reader["Password"].ToString(),
Address = reader["Address"].ToString(),
};
list.Add(b);
}
reader.Close();
}
dbConnection.Close();
}
}
catch (Exception ex)
{
string tmp = ex.Message;
}
return list.ToArray();
} // GetUsers
private static string Sanitize(string term)
{
Regex rgx = new Regex(#"[^\p{L}\p{N} ]+"); // \p{L} matches Unicode letters while \p{N} matches Unicode digits
term = rgx.Replace(term, ""); // Strip anything that isn't a letter or digit
return term;
} // Sanitize
private SQLiteConnection OpenDBConnection()
{
ConfigReader config = new ConfigReader();
string dataRoot = config.GetString(CONFIG_DATA_ROOT, #"C:/");
string dataDb = dataRoot + "/" + config.GetString(CONFIG_DATABASE, #"");
//string dataDb = dataRoot + "/" + databaseID;
string connectionString = String.Format("Data Source={0};Version=3;", dataDb);
SQLiteConnection dbConnection = new SQLiteConnection(connectionString);
dbConnection.Open();
return dbConnection;
} // OpenDBConnection
/// <summary>
/// Adds access control headers to service methods. One will need to add this when using
/// the Development Server which does not use system.webServer section of the Web.config
/// file and thus add the custom headers in there.
/// </summary>
private void AddAccessControlHeaders()
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Authorization, Content-Type");
} // AddAccessControlHeaders
private readonly string CONFIG_DATA_ROOT = "DataRoot";
private readonly string CONFIG_DATABASE = "Database";
private readonly string CONFIG_REALM = "Realm";
private readonly Guid serviceID;
} // class
}
Web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="DataRoot" value="C:/Users/delm959/Documents/Database"/>
<add key="Database" value="TestDatabase.db"/>
<add key="Realm" value="Boutique Cassee"/>
</appSettings>
<!--
For a description of web.config changes for .NET 4.5 see http://go.microsoft.com/fwlink/?LinkId=235367.
The following attributes can be set on the <httpRuntime> tag.
<system.Web>
<httpRuntime targetFramework="4.5" />
</system.Web>
-->
<system.web>
<customErrors mode="Off"/>
<compilation debug="true" targetFramework="4.5"/>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="CacheFor1200Seconds" duration="1200" varyByParam="none" varyByHeader="Accept"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="DefaultEndPointBehavior">
<dataContractSerializer maxItemsInObjectGraph="10000"/>
</behavior>
<behavior name="RESTEndPointBehavior">
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="WebHttpBindingConfig">
<!-- Comment out the security for HTTP; uncomment the security for HTTPS -->
<!--<security mode="Transport">
<transport clientCredentialType="None" />
</security>-->
</binding>
</webHttpBinding>
<basicHttpBinding>
<binding name="BasicHttpBindingConfig">
<readerQuotas/>
<!--
<security mode="None"/>
-->
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="SoulInfoService.Service">
<endpoint address="" behaviorConfiguration="RESTEndPointBehavior"
binding="webHttpBinding" bindingConfiguration="WebHttpBindingConfig"
bindingNamespace="http://www.example.org/Samples" contract="SoulInfoService.IService" />
<endpoint address="soap" behaviorConfiguration="DefaultEndPointBehavior"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBindingConfig"
bindingNamespace="http://www.example.org/Samples" contract="SoulInfoService.IService" />
<endpoint address="mex" binding="mexHttpBinding" bindingNamespace="http://www.example.org/Samples"
contract="IMetadataExchange" />
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Request-Method" value="OPTIONS, GET, POST"/>
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Headers" value="Authorization, Content-Type"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
This is a quite good tutorial how to create RESTful service with WCF which uses JSON formatter.
http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide

How to set webservice endpoint address at runtime?

I want to connect to a webservice url which is provided at runtime when user logs in. so i need to set Endpoint.Address in app.config at runtime.
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri(txtURL.text.trim());
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.Close();
I placed this code on button click ,and gets the value of uri from textbox. Code is executing correctly and then getting an error message
"Address property on channelfactory.endpoint was null"
my app.config is:
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="LoginServiceSoap" />
</basicHttpBinding>
</bindings>
<client>
<!--<endpoint address="http://localhost:3073/LoginService.asmx" binding="basicHttpBinding"-->
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="LoginServiceSoap" contract="LoginService.LoginServiceSoap"
name="LoginServiceSoap" />
</client>
</system.serviceModel>
</configuration>
I've done something similar in a recent project, where I only wanted to set the endpoint and authentication programatically and not use the config file at all:
public static class ServiceClientFactory
{
public static HttpBindingBase BuildNavisionBinding(string endpointUrl)
{
//http://blog.randomdust.com/index.php/2010/10/could-not-establish-trust-relationship-for-the-ssl-tls-secure-channel/
//http://www.codeproject.com/Forums/1649/Csharp.aspx?fid=1649&df=90&mpp=25&sort=Position&select=3126652&tid=3121885
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate
{
return true;
});
if (endpointUrl.ToLower().StartsWith("https"))
{
var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.MaxReceivedMessageSize = int.MaxValue - 1;
return binding;
}
else
{
var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.MaxReceivedMessageSize = int.MaxValue - 1;
return binding;
}
}
public static TClient CreateClient<TClient, TChannel>(string endpoint, string username, string password)
where TClient : ClientBase<TChannel>
where TChannel : class
{
var client = (TClient)
Activator.CreateInstance(
typeof (TClient),
BuildNavisionBinding(endpoint),
new EndpointAddress(endpoint));
if (null == client.ClientCredentials)
throw new Exception(
string.Format("Error initializing [{0}] client. Client Credentials object was null",
typeof(TClient).Name));
client.ClientCredentials.Windows.ClientCredential =
new NetworkCredential(
username,
password);
client.ClientCredentials.Windows.AllowedImpersonationLevel =
TokenImpersonationLevel.Delegation;
client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 0, 4, 0);
client.Endpoint.Binding.ReceiveTimeout = new TimeSpan(0, 4, 0);
client.Endpoint.Binding.OpenTimeout = new TimeSpan(0, 0, 4, 0);
return client;
}
So from your example:
var client = ServiceClientFactory.CreateClient<EchoServiceClient, IEchoServicePort(txtUrl.text.trim(), /* authentication */);

Trying to read web.config file for an IIS site from a Windows service

I am trying to look for a special web.config file for a web site installed on a local IIS. I do this search from a Windows service. I do the following:
using (ServerManager serverManager = new ServerManager())
{
for (int r = 0; r < serverManager.Sites.Count; r++)
{
string strSiteName = serverManager.Sites[r].Name;
ApplicationCollection arrApps = serverManager.Sites[r].Applications;
for (int a = 0; a < arrApps.Count; a++)
{
Microsoft.Web.Administration.Application aa = arrApps[a];
foreach (VirtualDirectory vd2 in aa.VirtualDirectories)
{
string strPhysPath = Environment.ExpandEnvironmentVariables(vd2.PhysicalPath);
int rr = 0;
try
{
Configuration cnfg = serverManager.GetWebConfiguration(strSiteName, strPhysPath);
if (cnfg != null)
{
string swww = getWebConfigGeneralParamValue(cnfg, "SpecNodeName");
}
}
catch
{
//Error
}
}
}
}
Where,
public static string getWebConfigGeneralParamValue(Configuration config, string strParamKey)
{
string strRes = null;
try
{
ConfigurationSection configSection1 = config.GetSection("configuration");
if (configSection1 != null)
{
ConfigurationElement configGeneralParams = configSection1.GetChildElement("GeneralParams");
if (configGeneralParams != null)
{
ConfigurationElementCollection configCol = configSection1.GetCollection();
if (configCol != null)
{
strRes = configCol[strParamKey].ToString();
}
}
}
}
catch(Exception ex)
{
strRes = null;
}
return strRes;
}
and the web.config file that should be recognized by this script is something like this:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<!-- regular ASP.NET config stuff -->
<GeneralParams>
<param key="SpecNodeName" value="Special Node Value"/>
</GeneralParams>
</configuration>
But what I get is that config.GetSection("configuration"); throws this exception:
{"Filename:
\\?\C:\inetpub\wwwroot\C:\Users\Dev\Desktop\CSharp\MyTestWebApp\MyTestWebApp\web.config\r\nError:
The configuration section 'configuration' cannot be read because it is
missing a section declaration\r\n\r\n"}
Any idea how to make it work?
You need not to target configuration, you need to target that particular node from where you need to get your data. here is the example.
using(ServerManager mgr = ServerManager.OpenRemote("Some-Server")) {
Configuration config = mgr.GetWebConfiguration("site-name", "/test-application");
ConfigurationSection appSettingsSection = config.GetSection("appSettings");
ConfigurationElementCollection appSettingsCollection = appSettingsSection.GetCollection();
ConfigurationElement addElement = appSettingsCollection.CreateElement("add");
addElement["key"] = #"NewSetting1";
addElement["value"] = #"SomeValue";
appSettingsCollection.Add(addElement);
serverManager.CommitChanges();
}
I am feeling, if you have web.config why you want to use ServerManager.
Take a look at below code, this I have been using in my code and it works as a charm.
What it does is it loads web.config in readable format.
var assemblyPath = Path.GetDirectoryName(typeof (ConfigurationTests).Assembly.Location);
string webConfigPath = MyPath;
string directory = System.IO.Path.GetFullPath(Path.Combine(assemblyPath,webConfigPath));
Console.WriteLine(directory);
Assert.That(Directory.Exists(directory));
VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(directory, true);
WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
System.Configuration.Configuration webConfig = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
var connectionString = webConfig.ConnectionStrings.ConnectionStrings["ConnectionString"].ConnectionString;
Console.WriteLine("Connection String:");
Console.WriteLine(connectionString);
Console.WriteLine("AppSettings:");
foreach (var key in webConfig.AppSettings.Settings.AllKeys)
{
Console.WriteLine("{0} : {1}", key, webConfig.AppSettings.Settings[key].Value);
}

Categories