Asmx Web Service Basic Authentication in Asp.net Core Web Application - web-services

I created a Asmx Web service and host it in IIS, in MVC, I could call it from below code:
BasicWebService.WebService1 client = new BasicWebService.WebService1();
client.Credentials = new System.Net.NetworkCredential("user", "pwd","domain");
string result = client.HelloWorld();
But, I failed to mark it work under Asp.net Core.
Here is the code what I have tried.
ServiceReference1.WebService1SoapClient client = new ServiceReference1.WebService1SoapClient(ServiceReference1.WebService1SoapClient.EndpointConfiguration.WebService1Soap);
client.ClientCredentials.UserName.UserName = "xx";
client.ClientCredentials.UserName.Password = "xx";
//string USER = "xx";
//string PASSWORD = "xx";
//string Domain = "xx";
//NetworkCredential netCredential = new NetworkCredential(USER, PASSWORD,Domain);
////client.Credentials = new System.Net.NetworkCredential("xx", "xx", "xx");
//client.ClientCredentials.Windows.ClientCredential = netCredential;// netCredential.GetCredential(new Uri("http://localhost/WCFBasicSecurity/WebService1.asmx"), "Basic");
ServiceReference1.HelloWorldResponse result =client.HelloWorldAsync().Result;

Got solution from GitHub, thanks for the suggestion from hongdai. Modify the generated reference.cs with below:
public WebService1SoapClient(EndpointConfiguration endpointConfiguration) :
base(WebService1SoapClient.GetBindingForEndpoint(endpointConfiguration), WebService1SoapClient.GetEndpointAddress(endpointConfiguration))
{
this.Endpoint.Name = endpointConfiguration.ToString();
this.ChannelFactory.Credentials.UserName.UserName = "xx\xx";
this.ChannelFactory.Credentials.UserName.Password = "xxxx";
ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
}
private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap))
{
//Transport Security
System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.Transport);
result.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Basic;
result.MaxBufferSize = int.MaxValue;
result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
result.MaxReceivedMessageSize = int.MaxValue;
result.AllowCookies = true;
return result;
}
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap12))
{
System.ServiceModel.Channels.CustomBinding result = new System.ServiceModel.Channels.CustomBinding();
System.ServiceModel.Channels.TextMessageEncodingBindingElement textBindingElement = new System.ServiceModel.Channels.TextMessageEncodingBindingElement();
textBindingElement.MessageVersion = System.ServiceModel.Channels.MessageVersion.CreateVersion(System.ServiceModel.EnvelopeVersion.Soap12, System.ServiceModel.Channels.AddressingVersion.None);
result.Elements.Add(textBindingElement);
System.ServiceModel.Channels.HttpTransportBindingElement httpBindingElement = new System.ServiceModel.Channels.HttpTransportBindingElement();
httpBindingElement.AllowCookies = true;
httpBindingElement.MaxBufferSize = int.MaxValue;
httpBindingElement.MaxReceivedMessageSize = int.MaxValue;
result.Elements.Add(httpBindingElement);
return result;
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
}
private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap))
{
return new System.ServiceModel.EndpointAddress("https://localhost/WCFBasicSecurity/WebService1.asmx");
//return new System.ServiceModel.EndpointAddress("http://localhost/WCFBasicSecurity/WebService1.asmx");
}
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap12))
{
return new System.ServiceModel.EndpointAddress("http://localhost/WCFBasicSecurity/WebService1.asmx");
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
}
Reference:https://github.com/dotnet/wcf/issues/1812

Related

mvc 5 does not delete a cookie

I am trying to delete all cookies from the responder,
the function is inside a service project.
code:
int limit = HttpContext.Current.Request.Cookies.Count;
for (int i = 0; i < limit; i++)
{
cookieName = HttpContext.Current.Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Value = null;
aCookie.Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.Response.Cookies.Add(aCookie)
}
but the response only adds more cookies with the same name. How do I fix this?
Try this:
string[] myCookies = Request.Cookies.AllKeys;
foreach (string cookie in myCookies)
{
Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
}
Edit: this suggestion is based on the guestimate that it has to do with you adding the cookie to the response instead of updating the one that's already present.
after a lot of head banging I finaly noticed that while creating the cookie as followed it did the trick
cookie = new HttpCookie(CookieName, CustId);
declaring the cookie in any other manner didn't work,
for example :
int limit = HttpContext.Current.Request.Cookies.Count;
for (int i = 0; i < limit; i++)
{
cookieName = HttpContext.Current.Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Value = null;
aCookie.Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.Response.Cookies.Add(aCookie);
}
or
var cookie = HttpContext.Current.Response.Cookies[CookieName];
if(cookie == null)
{
cookie = new HttpCookie(CookieName, CustId);
}
else
{
cookie.Expires = DateTime.Now.AddDays(-100);
HttpContext.Current.Response.Cookies.Add(cookie);
//HttpContext.Current.Session.Clear();
}

Transaction Advance Search for Sales Order in NetSuite returning Errors when otherRefNum Operator used

Any idea why the below code would return an error(Failure) for its status?
private SearchResult getTxns()
{
TransactionSearchAdvanced tsa = new TransactionSearchAdvanced();
tsa.columns = new TransactionSearchRow();
tsa.columns.basic = new TransactionSearchRowBasic();
tsa.columns.basic.tranId = new SearchColumnStringField[] { new SearchColumnStringField() };
tsa.criteria = new TransactionSearch();
tsa.criteria.basic = new TransactionSearchBasic();
tsa.criteria.basic.mainLine = new SearchBooleanField();
tsa.criteria.basic.mainLine.searchValue = true;
tsa.criteria.basic.mainLine.searchValueSpecified = true;
tsa.criteria.basic.type = new SearchEnumMultiSelectField();
tsa.criteria.basic.type.#operator = SearchEnumMultiSelectFieldOperator.anyOf;
tsa.criteria.basic.type.operatorSpecified = true;
tsa.criteria.basic.type.searchValue = new string[] { "_salesOrder" };
tsa.criteria.basic.otherRefNum = new SearchTextNumberField();
tsa.criteria.basic.otherRefNum.#operator = SearchTextNumberFieldOperator.equalTo;
tsa.criteria.basic.type.operatorSpecified = true;
tsa.criteria.basic.type.searchValue = new string[] { "BBnB 1001" };
SearchResult sr = _service.search(tsa);
return sr;
}
The following is the error that is returned in the results.
Status Code: INVALID_SEARCH_OPERATOR
Status Message: You need to provide a valid search field operator.
However, this operator appears in the NetSuite UI itself when I do a search. Also, I find it in the NetSuite documentation here.
I am using v2013_1_0 for the webservices version of the wsdl.
SOLUTION
Solution found to be in the last block of code. Was attempting to set otherRefNum and was referencing Type. Here is the corrected code.
private SearchResult getTxns()
{
TransactionSearchAdvanced tsa = new TransactionSearchAdvanced();
tsa.columns = new TransactionSearchRow();
tsa.columns.basic = new TransactionSearchRowBasic();
tsa.columns.basic.tranId = new SearchColumnStringField[] { new SearchColumnStringField() };
tsa.criteria = new TransactionSearch();
tsa.criteria.basic = new TransactionSearchBasic();
tsa.criteria.basic.mainLine = new SearchBooleanField();
tsa.criteria.basic.mainLine.searchValue = true;
tsa.criteria.basic.mainLine.searchValueSpecified = true;
tsa.criteria.basic.type = new SearchEnumMultiSelectField();
tsa.criteria.basic.type.#operator = SearchEnumMultiSelectFieldOperator.anyOf;
tsa.criteria.basic.type.operatorSpecified = true;
tsa.criteria.basic.type.searchValue = new string[] { "_salesOrder" };
tsa.criteria.basic.otherRefNum = new SearchTextNumberField();
tsa.criteria.basic.otherRefNum.#operator = SearchTextNumberFieldOperator.equalTo;
tsa.criteria.basic.otherRefNum.operatorSpecified = true;
tsa.criteria.basic.otherRefNum.searchValue = "BBnB 1001";
SearchResult sr = _service.search(tsa);
return sr;
}
The problem is with your SearchEnumMultiSelectField operator. equalto is not a valid operator for this filter; you will need to use anyOf instead.
-- EDIT - Adapated from original comment --
A SearchTextNumberField does not accept an array of Strings. Instead try tsa.criteria.basic.otherRefNum.searchValue = "BBnB 1001";

Getting org.xmlpull.v1.XmlPullParserException for SOAP connection in BlackBerry

I am using ksoap2.jar in my application for webservice call.
While conneting, to the server it is giving the below error when i am testing using Wi-fi or simulator:
org.xmlpull.v1.XmlPullParserException: unexpected type (position:END_DOCUMENT null#1:0 in java.io.InputStreamReader#6111a1f1)
And when i am testing using SIM Card, it is throwing this error: java.io.InterruptedIOException: Local connection timed out after ~ 120000
I have written the below code for this webservice connection:
SoapObject rpc = new SoapObject(serviceNamespace, methodName);
rpc.addProperty("UserID", "1");
rpc.addProperty("UserName", "xyz");
rpc.addProperty("ContactNo", "9014567890");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = rpc;
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.ENC;
HttpTransport ht = new HttpTransport(serviceUrl + getConnectionString().trim());
ht.debug = true;
System.out.println("debug true ------- ");
ht.setXmlVersionTag(" version=\"1.0\" encoding=\"UTF-8\"?>");
SoapObject response = null;
try
{
ht.call(soapAction, envelope);
response = (SoapObject )envelope.getResponse();
String resultbody = response.getProperty("updateUserDetailResult").toString();
}
catch(org.xmlpull.v1.XmlPullParserException ex2){
resultLbl.setText(ex2.toString());
}
catch(Exception ex){
String bah = ex.toString();
resultLbl.setText(bah);
}
/**
* Looks through the phone's service book for a carrier provided BIBS network
*
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid()
{
net.rim.device.api.servicebook.ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++)
{
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
/**
* Getting the connection string based on the connection
* #return
*/
public static String getConnectionString()
{
String connectionString = null;
// Wifi is the preferred transmission method
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null)
{
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
connectionString = ";deviceside=true";
}
else
{
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=false;connectionUID=" + carrierUid + ";ConnectionType=";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
}
// In theory, all bases are covered so this shouldn't be reachable.
else
{
connectionString = ";deviceside=true";
}
return connectionString;
}
I am using the preverified ksoap jar file(ksoap2-j2me-core-prev-2.1.2.jar).
I am not getting exactly where it is going wrong. I have searched in the forum but did not get the proper solution.
Thanks.

Blackberry soap response

I am trying to consume .net webservices, and I can establish the connection. However this is the response I am getting:
[0.0] anyType{NewDataSet=anyType{Table=anyType{Card_ID_PK=2243; PAN=63369610009001016; Expiry_Date[0.0] =15/06/2015; Embossed_Name=IDL IG scheme;
I want them to split and display it as a table. I searched in google and I found some methods like split() but that can only delimit single character and also I need the way to remove the characters and use them as key value pair which is used for .
Here is my code for soap:
// TODO Auto-generated method stub
if (DeviceInfo.isSimulator()) {
URL = URL + ";deviceSide=true";
}
SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME); //soap object to open the namespace and method name
rpc.addProperty("CH_ID","15");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = rpc;
System.out.println("envelope response"+envelope.bodyOut.toString());
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
System.out.println("in soap");
envelope.setOutputSoapObject(rpc);
HttpTransport ht = new HttpTransport(URL);
ht.debug = true;
try {
System.out.println("int try");
ht.call(SOAP_ACTION, envelope);
System.out.println("int try");
SoapObject resultProperties = (SoapObject) envelope.getResponse();
System.out.println("IN TRY");
String res=resultProperties.getProperty(1).toString();
System.out.println("Response"+res);
String[] pattern={"{","}","anytype","Table",";"};
String replacement="";
String array=replaceall(res,pattern,replacement);
System.out.println(" array element:"+array[i]);
replace all method :
public String replaceall(String str, String[] pattern, String replacement)
{
if(str==null)
{
return "";
}
StringBuffer sb=new StringBuffer();
int index=-1;
String workingSource = str;
for(int i=0;i<pattern.length;i++)
{
while ((index = workingSource.indexOf(pattern[i])) != -1)
{
sb.append(workingSource.substring(0, index));
sb.append(replacement);
sb.append(workingSource.substring(index + pattern[i].length()));
workingSource = sb.toString();
sb.delete(0, sb.length());
}
}
return workingSource;
}
}

List of windows users remotely

I would like to know how to retrieve the list of users that are logged onto a Remote machine. I can do it with qwinsta /server:xxxx, but would like to do it in C#.
check out wmi in .net under system.management.
something like:
ConnectionOptions conn = new ConnectionOptions();
conn.Authority = "ntdlmdomain:NAMEOFDOMAIN";
conn.Username = "";
conn.Password = "";
ManagementScope ms = new ManagementScope(#"\\remotecomputer\root\cimv2", conn);
ms.Connect();
ObjectQuery qry = new ObjectQuery("select * from Win32_ComputerSystem");
ManagementObjectSearcher search = new ManagementObjectSearcher(ms, qry);
ManagementObjectCollection return = search.Get();
foreach (ManagementObject rec in return)
{
Console.WriteLine("Logged in user: " + rec["UserName"].ToString());
}
You may not need the ConnectionOptions...
I ended up using the qwinsta /server:server1 command from C# -- it was much easier
thanks Ken
All this checks all 8 servers at the same time -- I put the result in sql server
but you can do what ever you want
query_citrix.bat script
cd C:.......\bin\citrix_boxes
qwinsta -server:servername or ip > servername.txt
string sAppCitrixPath = Application.StartupPath.ToString() + "\\citrix_boxes\\";
//Run Script for current citrix boxes
Process proc = new Process();
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = sAppCitrixPath + "query_citrix.bat";
proc.StartInfo = si;
proc.Start();
proc.WaitForExit();
int exitCode = proc.ExitCode;
proc.Close();
if (exitCode == 0)
{
//Execute update who is on the Citrix_Boxes Currently
DirectoryInfo dic = new DirectoryInfo(sAppCitrixPath);
FileInfo[] fic = dic.GetFiles("*.txt");
for (int i = 0; i < fic.Length; i++)
{
ParseQWinStaServerFile(fic[i].FullName.ToString(), fic[i].Name.ToString().ToUpper().Replace(".TXT",""));
File.Delete(fic[i].FullName.ToString());
}
}
private void ParseQWinStaServerFile(string sLocation,string sServer)
{
using (StreamReader sr = File.OpenText(sLocation))
{
string sRecord = String.Empty;
char[] cSep = new char[] {' '};
bool bFirst = true;
while ((sRecord = sr.ReadLine()) != null)
{
if (bFirst == false)
{
string[] items = sRecord.Split(cSep, StringSplitOptions.RemoveEmptyEntries);
//Make sure all columns are present on the split for valid records
if (sRecord.Substring(19, 1) != " ") // check position of user id to see if it's their
{
//Send the user id and server name where you want to.
//here is your user
id = items[1].ToString().ToLower().Trim()
//here is your server
};
}
else
{
bFirst = false;
}
}
}
}