I have created a vsto application that calls a webservice. everything seems to work just fine, but i would like to extend the functionality to call the test service version of my production service.
code snippet that works that calls my test service.
//how do i change here to be dynamic?
npfunctions.finfunctions service = new npfunctions.finfunctions();
var Results = service.ValidateFoapal(index.ToArray(), fund.ToArray(), org.ToArray(), prog.ToArray(), acct.ToArray(), row.ToArray());
/* if their are no error then return a "Y" for success.*/
if (Results.Count() < 0) { return LocallErrorInd; }
/*well we have encountered errors lets adjust the spreadsheet to notify the user.*/
else{
//REMOVE ANY VISUAL ERRORS
Microsoft.Office.Interop.Excel.Range delRng = Globals.ThisAddIn.Application.Range["R:S"];
delRng.Delete(XlDeleteShiftDirection.xlShiftToLeft);
for (int i = 0; i < Results.Count(); i++)
{//set the error indicator
LocallErrorInd = "Y";
//account error:
if (Results[i].FVALJOR_FUND_WARNING == "Y")
{
Microsoft.Office.Interop.Excel.Range WrkRng = Globals.ThisAddIn.Application.Range[Results[i].FVALJOR_ROW];
WrkRng.Offset[0, 17].Value2 = "Invalid Account";
}
i have seen this post How can I dynamically switch web service addresses in .NET without a recompile?
but it requires me to change my config file i would really like to change the service variable to point to another location based on a variable and basically flip from prod to test on my command. as i see it right now it appears that i would have to duplicate the code but i know there has got to be a better way. i like it to be something like.
if (TestBtn.Checked == true)
{
npfunctions.finfunctions service = new npfunctions.finfunctions();
Results = service.ValidateFoapal(index.ToArray(), fund.ToArray(), org.ToArray(), prog.ToArray(), acct.ToArray(), row.ToArray());
}
if (PrdBtn.Checked == true)
{
prdFunctions.finfunctions service = new prdFunctions.finfunctions();
Results = service.ValidateFoapal(index.ToArray(), fund.ToArray(), org.ToArray(), prog.ToArray(), acct.ToArray(), row.ToArray());
}
/* if their are no error then return a "Y" for success.*/
if (Results.Count() < 0) { return LocallErrorInd; }
Does your service object not have a URL property?
2nd option, you can use a config file transformation so you do not need to manually change the settings(after the intial setup of course).
npfunctions.finfunctions service = new npfunctions.finfunctions();
if (TestBtn.Checked == true)
{
service.url="<testurl>";
}
else
{
service.url="<produrl>";
}
Results = service.ValidateFoapal(index.ToArray(), fund.ToArray(), org.ToArray(), prog.ToArray(), acct.ToArray(), row.ToArray());
In our test client we have a drop-down to select between dev or tst. We also have buttons to select proxy or net.tcp. (We have many different people using our service using different methods).
In the app.config the names of the endpoints correlate with different selectable options.
Eg. name="BasicHttpBinding_IInterface_PROXY_DEV"
You can then dynamically build up which endpoint you would like to use and go with that.
Related
I need to read all users from the AD. Here is code that I am using:
using Novell.Directory.Ldap;
using Novell.Directory.Ldap.Controls;
using System.Linq;
namespace LdapTestApp
{
class Program
{
static void Main()
{
LdapConnection ldapConn = new LdapConnection();
ldapConn.SecureSocketLayer = true;
ldapConn.Connect(HOST, PORT);
try
{
var cntRead = 0;
int? cntTotal = null;
var curPage = 0;
ldapConn.Bind(USERNAME, PASSWORD);
do
{
var constraints = new LdapSearchConstraints();
constraints.SetControls(new LdapControl[]
{
new LdapSortControl(new LdapSortKey("sn"), true),
new LdapVirtualListControl("sn=*", 0, 10)
});
ILdapSearchResults searchResults = ldapConn.Search(
"OU=All Users,DC=homecredit,DC=ru",
LdapConnection.ScopeSub,
"(&(objectCategory=person)(objectClass=user))",
null,
false,
constraints
);
while (searchResults.HasMore() && ((cntTotal == null) || (cntRead < cntTotal)))
{
++cntRead;
try
{
LdapEntry entry = searchResults.Next();
}
catch (LdapReferralException)
{
continue;
}
}
++curPage;
cntTotal = GetTotalCount(searchResults as LdapSearchResults);
} while ((cntTotal != null) && (cntRead < cntTotal));
}
finally
{
ldapConn.Disconnect();
}
}
private static int? GetTotalCount(LdapSearchResults results)
{
if (results.ResponseControls != null)
{
var r = (from c in results.ResponseControls
let d = c as LdapVirtualListResponse
where (d != null)
select (LdapVirtualListResponse)c).SingleOrDefault();
if (r != null)
{
return r.ContentCount;
}
}
return null;
}
}
}
I used this question Page LDAP query against AD in .NET Core using Novell LDAP as basis.
Unfortunatelly I get this exception when I am trying to recieve the very first entry:
"Unavailable Critical Extension"
000020EF: SvcErr: DSID-03140594, problem 5010 (UNAVAIL_EXTENSION), data 0
What am I doing wrong?
VLVs are browsing indexes and are not directly related to the possibility or not to browse large numbers of entries (see generic documentation). So even if this control would be activated on your AD, you wouldn't be able to retrieve more than 1000 elements this way :
how VLVs work on AD
MaxPageSize is 1000 by default on AD (see documentation)
So what you can do:
use a specific paged results control, but it seems that the Novell C# LDAP library does not have one
ask you the question: "is this pertinent to look for all the users in a single request?" (your request looks like a batch request: remember that a LDAP server is not designed for the same purposes than a classic database - that can easily return millions of entries - and that's why most of LDAP directories have default size limits around 1000).
The answer is no: review your design, be more specific in your LDAP search filter, your search base, etc.
The answer is yes:
you have a single AD server: ask your administrator to change the MaxPageSize value, but this setting is global and can lead to several side effects (ie. what happens if everybody start to request all the users all the time?)
you have several AD servers: you can configure one for specific "batch like" queries like the one you're trying to do (so large MaxPageSize, large timeouts etc.)
I had to use approach described here:
https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard/issues/71#issuecomment-420917269
The solution is far from being perfect but at least I am able to move on.
Starting with version 3.5 the library supports Simple Paged Results Control - https://ldapwiki.com/wiki/Simple%20Paged%20Results%20Control - and the usage is as simple as ldapConnection.SearchUsingSimplePaging(searchOptions, pageSize) or ldapConnection.SearchUsingSimplePaging(ldapEntryConverter, searchOptions, pageSize) - see Github repo for more details - https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard and more specifically use the tests as usage samples.
I have an issue adding some code in SAP cloud application.
I have to retrieve the ID of the employee that creates an order in C4C and print it in a camp z (or "label") called CreatedECC. When an emp creates this order a form is created where you can see emp name, date, delivery status, creation date, created by, etc... here is where the label was added for me to retrieve the userID and print it. Im not sure if someone can help me with the code... there is so much i can share.
Im new to javascript (and SAP cloud app) so i dont entirely understand the code and that´s why i need help
The code is:
import ABSL;
import AP.CRM.Global;
var query_mapping;
var sel_param_mapping;
var result_mapping;
this.IsConsistent = true;
var i = 0;
foreach (var item in this.Item)
{
if (!item.Plant.IsInitial())
{
item.Plant = item.Plant.ToUpperCase();
query_mapping = Plants.QueryByElements;
sel_param_mapping = query_mapping.CreateSelectionParams();
sel_param_mapping.Add(query_mapping.PlantID, "I", "EQ", item.Plant);
result_mapping = query_mapping.Execute(sel_param_mapping);
if (!result_mapping.GetFirst().IsSet())
{
raise MsgNoFoundPlantID.Create("E", item.Plant);
i = 1;
}
}
}
if (i == 1)
{
this.IsConsistent = false;
}
I spoke with a partner via skype (i think he helped with the development) and he told me the steps i need to follow wich are:
Create the patch in the corresponding development. Done.
Add a reference object and select the customizing camp that was created for you
Add your code so that a variable would be equal to the value Context.GetCurrentIdentityUUID. Through that value you get the userID you need to print in the customizing camp... And that is all
We're creating a WPF app in which we execute python scripts from different Test Stations and show the output in its corresponding output panel, To run the scripts in parallel we are using Task but when we run the scripts in parallel from the stations, We are getting the output of other stations also into the station that is started first, we're using the following code,
private void ZmqStatusListener(string endPoint)
{
using (Context context = new Context())
{
StatusPort = string.Empty;
TestResultPort = string.Empty;
using (Socket server = context.Socket(SocketType.REP))
{
try
{
if (isStatusContextActive == false || isPortChanged == true)
{
server.Bind(endPoint);
isStatusContextActive = true;
}
}
catch (ZMQ.Exception ex)
{
if (ex.Errno != 100)
{
string IPCPort = _globalParameters.GlbParam.GlbParamIpcStartPort;
if (IPCPort == string.Empty)
{
IPCPort = "0";
}
if (endPoint == EditorConstants.PortAddress.PortPrefix + IPCPort)
{
StatusPort = endPoint;
TestReultError = EditorConstants.CommonMessageTypes.TestReultError + ex.Message + EditorConstants.CommonMessageTypes.StackTraceMessage + ex.StackTrace;
}
StopExecOfScript(default(object));
isCancelledtask = true;
ScriptStatusDesc = new ScriptStatusDesc()
{
Status = "Failed",
statusDescription = "Failed"
};
}
}
while (true)
{
string message = server.Recv(Encoding.UTF8);
UpdateTestResults(message);
server.Send(" ACK", Encoding.UTF8);
// if (message == "Test Passed")
//break;
}
}
}
}
and for testing purpose we're breaking the while loop in this code based on a test message we kept in the python script, then we are able to get the output in the respective station correctly but this way we can only run in a synchronous fashion which we don't want as we require to run the test stations in parallel and the while loop should not break as it should be listening for the response.
We were able to solve the issue by getting clues doing a sample app to reproduce the issue and to first know whether our ClrZmq pattern was correct for us or not and it is correct. The resolution we followed is that when we needed to bind that data to its corresponding View's Model object in its ViewModel so had to retrieve View's DataContext which is of Type ISomeXViewModel for the particular TestStation using an Id of that TestStation we did this cos all of our TestStations are dynamically added and we even store it to be accessed wherever necessary. This issue was caused to due multiple instances of UserControls so we explicitly needed to update the TestStation manually with a little more effort.
Sample Code Snippet
private void BindTestResult(string xmlPayLoad)
{
// converting xmlPalLoad to a class/model object
ITestStationViewModel viewModel = (ITestStationViewModel)((IView)DynamicTestStationsGrid.Children[StationNumber].Content).DataContext;
// IView class has DataContext property so I am type casting the Content which is ContentControl to IView type first and later to ITestStationViewModel
viewModel.TestStationModel = xmlPayLoadModel;
}
Thanks.
i'm a beginner at developing a whole system so, need some approach guidance here folks. Hope you can help me! =)
In a try to create a log in schema, i have a Control class which keeps a list of logged users.
public static class ControleAcesso
{
private static List<Associado> associadosLogados = new List<Associado>();
public static Mensagens doLogin(Page pagina, String login, String senha)
{
Mensagens retorno = new Mensagens();
retorno = AcessoDAL.Login(login, senha);
if (retorno.Erros.Count() <= 0 && retorno.Objeto != null)
{
Associado assocLogado = new Associado();
Associados assocEncontrado = (Associados)retorno.Objeto;
assocLogado.ID = assocEncontrado.Associado;
assocLogado.Nome = assocEncontrado.Nome;
assocLogado.Nome_Fantasia = assocEncontrado.Nome_Fantasia;
assocLogado.Data_Inclusao = assocEncontrado.Data_Inclusao;
assocLogado.Email = assocEncontrado.Email;
assocLogado.Data_Alteracao = assocEncontrado.Data_Alteracao;
assocLogado.Login = assocEncontrado.Login;
assocLogado.Senha = assocEncontrado.Senha;
assocLogado.CGC_CPF = assocEncontrado.CGC_CPF;
assocLogado.SessionID = pagina.Session.SessionID;
var associadoJaLogado = associadosLogados.Where(x => x.ID == assocLogado.ID).FirstOrDefault();
if (associadoJaLogado != null)
{
pagina.Session.Remove(associadoJaLogado.SessionID);
associadosLogados.Remove(associadoJaLogado);
}
associadosLogados.Add(assocLogado);
}
return retorno;
}
}
So, this method basicaly do the login call to a Data Access Layer class. If the log in returns a user, i do Add this user to my list.
So, to later know my logged in users and retrieve data about then just using my session ID, i do some management in the list. Just the basic. Removing the logged in one and adding the new one.
The problem, as you probably noticed, is that, when i have two requests for the same credentials at the "same" time, it would allow the user to log in two times.
So, is this the best practice for log in schemes? Would you guys suggest me to change something?
I'm using ASP.NET Web Forms with C#.
Thank you in advice.
Unless you explicitly want to force your users to use your application with one device at a time, you should not worry about the possibility that they might log in. So this is a problem if and only if it can violate one of your terms.
Below I have some code that that I cannot Unit test because it tries to read settings from IIS7 and unfortunately our nightly build machine does not have IIS7. The only thing I can think of is to pass the ServerManager into the method, but then again in the caller I will have a ServerManager that will make that method unable to be unit tested. We use MOQ for our Mock library.
public ISection GetCurrentSettings(string location, Action<string> status)
{
#region Sanity Checks
if (string.IsNullOrEmpty(location))
{
throw new ArgumentNullException("location");
}
if (status == null)
{
throw new ArgumentNullException("status");
}
#endregion
ISection section = null;
_logger.Debug(string.Format("Retrieving current IIS settings for app at {0}.", location));
status("Getting current IIS settings.");
using (ServerManager manager = new ServerManager())
{
var data = (from site in manager.Sites
from app in site.Applications
from vdir in app.VirtualDirectories
where vdir.PhysicalPath.Equals(location, StringComparison.CurrentCultureIgnoreCase)
select new {Website = site, App = app}).SingleOrDefault();
if (data == null)
{
_logger.Debug(string.Format("Could not find an application at {0} in IIS. Going to load the defaults instead.", location));
//ToDo possibly load defaults
}
else
{
_logger.Debug(string.Format("Application found in IIS with website: {0} and a path of {1}", data.Website.Name, data.App.Path));
int port =
data.Website.Bindings.Where(b => b.EndPoint != null).Select(b => b.EndPoint.Port).Single();
section = new IISSection
{
ApplicationPoolName = data.App.ApplicationPoolName,
VirtualDirectoryAlias = data.App.Path,
WebsiteName = data.Website.Name,
WebsiteRoot = data.App.VirtualDirectories[0].PhysicalPath,
Port = port.ToString(CultureInfo.InvariantCulture),
WillApply = true,
AnonymousUser = _userService.GetUserByType(UserType.Anonymous)
};
}
return section;
}
Without rewriting your code fully, the general idea would be to pass in an ISettingReader* (implemented as IisSettingReader), which would expose methods that would get the data you need from IIS. Then, you can stub in the ISettingReader to return what you need, by passing ISettingReader into the method/class
*Or, IServerManager as it seems to be the current name, but I am not sure if that is IIS specific
UPDATE
To be more specific, as Darin Dimitrov elaborated, you need to pull all of the dependencies outside of the method and pass them in via parameter/constructor/property injection. This will require a rewrite of the code as it stands in its current state.
If not (and I do suggest a rewrite), then you can use something like TypeMock, which supposedly can fake the dependencies INSIDE a class, but I have not used this myself and only know what I have read on it.
Use Moq.
This will allow you to create a mocked version of ISettings rather than having to create a real one. It has the added advantage of allowing you to specify your own functionality as well.