How to add ASP.net webservice directive to CodeDom generated .asmx file - asp.net

How can I add
<%# webservice class="MyNamespace.MyClass" ... %>
To the top of a CodeDom generated .asmx file?
Here's some code to fill this question out a bit more:
public void Generate<T>()
{
string[] importNameSpaces = new string[] { "System","CoreData","System.Web.Services", "System.Data", "System.Text", "System.Collections.Generic" };
targetUnit = new CodeCompileUnit();
CodeNamespace samples = new CodeNamespace(TargetNamespace);
foreach (string space in importNameSpaces)
{
samples.Imports.Add(new CodeNamespaceImport(space));
}
ClassName = typeof(T).Name;
CodeSnippetStatement WebServiceDirective = new CodeSnippetStatement("<%# WebService Language=\"C#\" CodeBehind=\"Plans.asmx.cs\" Class=\"" + TargetNamespace + "." + ClassName + "\" %>");
targetClass = new CodeTypeDeclaration(ClassName);
targetClass.IsClass = true;
targetClass.TypeAttributes =
TypeAttributes.Public;
targetClass.IsPartial = true;
CodeAttributeDeclaration WebServiceAtt = new CodeAttributeDeclaration(
new CodeTypeReference(
typeof(WebServiceAttribute)), new CodeAttributeArgument[]
{ new CodeAttributeArgument("Namespace",new CodeSnippetExpression(#"http://tempuri.org"))});
targetClass.CustomAttributes.Add(WebServiceAtt);
WebServiceAtt = new CodeAttributeDeclaration(
new CodeTypeReference(
typeof(WebServiceAttribute)),
new CodeAttributeArgument[]
{ new CodeAttributeArgument("ConformsTo", new CodeTypeReferenceExpression(WsiProfiles.BasicProfile1_1.GetType())) });
targetClass.CustomAttributes.Add(WebServiceAtt);
foreach (OperationType o in Enum.GetValues(typeof(OperationType)))
{
if (CoreData.Utility.SupportsOperation(typeof(T),o))
{
targetClass.Members.Add(createWebServiceMethod(typeof(T).Name,typeof(T).GetProperties(),o));
}
}
samples.Types.Add(targetClass);
targetUnit.Namespaces.Add(samples);
//targetUnit.StartDirectives.Add(WebServiceDirective);
CSharpCodeProvider provider = new CSharpCodeProvider();
IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(OutputDirectory + #"\" + targetClass.Name + ".asmx", false));
provider.GenerateCodeFromCompileUnit(targetUnit, tw, new CodeGeneratorOptions());
tw.Close();
}

CodeDom doesn't directly support generating ASMX files. It only supports languages such as C# and VB.
You'll have to insert the WebService directive manually. You might be able to do this by first writing the directive to the tw writer before passing it into the CodeDom provider.

Related

Passing the servername/Ldap inside "DirectoryEntry" Vs "PrincipalContext"

I have this action method inside my ASP.NET MVC-5 .net 4.6:-
public ActionResult UsersInfo2()
{
List<DomainContext> results = new List<DomainContext>();
try
{
// create LDAP connection object
DirectoryEntry myLdapConnection = createDirectoryEntry();
string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];
string ADusername = System.Web.Configuration.WebConfigurationManager.AppSettings["ADUserName"];
string ADpassword = System.Web.Configuration.WebConfigurationManager.AppSettings["ADPassword"];
using (var context = new DirectoryEntry("LDAP://mydomain.com:389/DC=mydomain,DC=com", ADusername, ADpassword))
using (var search = new DirectorySearcher(context))
{
SearchResult r = search.FindOne();
ResultPropertyCollection fields = r.Properties;
foreach (String ldapField in fields.PropertyNames)
string temp;
foreach (Object myCollection in fields[ldapField])
temp = String.Format("{0,-20} : {1}",
ldapField, myCollection.ToString());
}
}
using (var context = new PrincipalContext(ContextType.Domain, "mydomain.com", ADusername, ADpassword))
{
bool isvalid = context.ValidateCredentials("*******", "****************");
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return View(results);
}
so after around one day of testing i realize that for the DirectoryEntry I need to pass the server/ldap as follow ("LDAP://mydomain.com:389/DC=mydomain,DC=com", ADusername, ADpassword)) , while for the PrincipalContext we need to pass it as follow:- (ContextType.Domain, "mydomain.com", ADusername, ADpassword)).. so i can not pass the ldap inside the PrincipalContext nor the servrname only inside the DirectoryEntry .. so is this the case? or i am doing things wrongly ?
Thanks
You are correct.
The System.DirectoryServices.AccountManagement namespace (PrincipalContext, UserPrincipal, etc.) was created to simplify things. However, it just uses the System.DirectoryServices namespace (DirectoryEntry, etc.) in the background. (except for ValidateCredentials, which uses System.DirectoryServices.Protocols.LdapConnection).
I prefer to always use DirectoryEntry and friends because it gives me more control over performance. That's something I wrote an article about: Active Directory: Better performance

Is it possible to create a folder on the Alfresco site by using OpenCMIS API?

I have the Presentation Web Script (script A) and the Data Web Script (script B).
In the script A I build the dialog that interacts with the script B.
Here I am forming some path where the some file will be uploaded (group, year and number parameters define this path):
...
var submitHandler = function() {
var dataWebScriptUrl = window.location.protocol + '//' +
window.location.host + "/alfresco/s/ms-ws/script-b?guest=true";
var yearCombo = document.getElementById("year");
var year = yearCombo.options[yearCombo.selectedIndex].value;
var groupCombo = document.getElementById("group");
var group = groupCombo.options[groupCombo.selectedIndex].value;
var numberCombo = document.getElementById("number");
var number = numberCombo.value;
var uploadedFile = document.getElementById("uploadedFile");
var file = uploadedFile.files[0];
var formData = new FormData();
formData.append("year", year);
formData.append("group", group);
formData.append("number", number);
formData.append("uploadedFile", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", dataWebScriptUrl);
xhr.send(formData);
};
...
In script B, I'm using the Apache Chemistry OpenCMIS API to create a path in the CMIS-compatible Alfresco repository:
public class CustomFileUploader extends DeclarativeWebScript implements OpenCmisConfig {
...
private void retrievePostRequestParams(WebScriptRequest req) {
String groupName = null, year = null, number = null;
FormData formData = (FormData) req.parseContent();
FormData.FormField[] fields = formData.getFields();
for(FormData.FormField field : fields) {
String fieldName = field.getName();
String fieldValue = field.getValue();
if(fieldName.equalsIgnoreCase("group")) {
if(fieldValue.equalsIgnoreCase("services")) {
groupName = "Услуги";
...
}
firstLevelFolderName = "/" + groupName;
secondLevelFolderName = groupName + " " + year;
thirdLevelFolderName = number;
}
...
Folder firstLevelFolder =
createFolderIfNotExists(cmisSession, docLibFolder, firstLevelFolderName);
...
private Folder createFolderIfNotExists(Session cmisSession,
Folder parentFolder, String folderName) {
Folder subFolder = null;
for(CmisObject child : parentFolder.getChildren()) {
if(folderName.equalsIgnoreCase(child.getName())) {
subFolder = (Folder) child;
}
}
if(subFolder == null) {
Map<String, Object> props = new HashMap<>();
props.put("cmis:objectTypeId", "cmis:folder");
props.put("cmis:name", folderName);
subFolder = parentFolder.createFolder(props);
}
return subFolder;
}
private Folder getDocLibFolder(Session cmisSession, String siteName) {
String path = "/Sites/" + siteName + "/documentLibrary";
return (Folder) cmisSession.getObjectByPath(path);
}
private Session getCmisSession() {
SessionFactory factory = SessionFactoryImpl.newInstance();
Map<String, String> conf = new HashMap<>();
// http://localhost:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom
conf.put(SessionParameter.ATOMPUB_URL, ATOMPUB_URL);
conf.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
conf.put(SessionParameter.USER, USER_NAME);
conf.put(SessionParameter.PASSWORD, PASSWORD);
// "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl"
conf.put(SessionParameter.OBJECT_FACTORY_CLASS, OBJECT_FACTORY_CLASS);
conf.put(SessionParameter.REPOSITORY_ID, "-default-");
Session session = factory.createSession(conf);
return session;
}
...
It's all works well... But I need to create the directory structure on a specific site, e.g. "contracts-site", here:
/site/contracts-site/documentlibrary
When I specifying the following:
/Sites/contracts-site/documentLibrary/Услуги
/Sites/contracts-site/Услуги
/site/contracts-site/documentlibrary/Услуги
I get the following exception (depending on the path):
org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException: Object not found: /Sites/contracts-site/Услуги
When I specifying the following:
"/Услуги"
Everything works, but the directory structure is created outside the site...
How to create a folder on the Alfresco site by using OpenCMIS API?
Arn't you missing /company_home/ ?
This would lead to
/company_home/Sites/contracts-site/documentLibrary/Услуги
Just accidentally found the solution. Works perfectly if specify the following path:
// locate the document library
String path = "/Сайты/contracts-site/documentLibrary";
Ie, "Сайты" instead of "Sites"... (Cyrillic alphabet)
I'm using ru_RU locale and UTF-8 encoding. Then this example also works.

Why does R.NET work locally but stop working in IIS?

I have an ASP.NET MVC application that sends parameters to an R script, the R script then generates a file and puts it in a folder locally. The process works perfectly on my local machine through Visual Studio but goes in and out after I publish and use IIS. Below is how I am initializing R.NET and getting these values from my view via AJAX.
I also have placed both of these PATHs in my system environment variables.
If anyone knows why IIS only works right after I restart my OS and then stops working shortly after I would greatly appreciate it. Seems odd that I have no problems in Visual Studio that I face in IIS.
[HttpGet]
public JsonResult Index1(string modelTypes = null, string fileNames = null, string[] locations = null, string lowerLimits = null, string upperLimits = null, string areas = null, string productivities = null, string[] fobs = null)
{
#ViewBag.UserName = System.Environment.UserName;
string userName = #ViewBag.UserName;
//Declare field parameters
var strModelTypeValue = modelTypes;
string strFileName = fileNames;
var strLocationValue = locations;
var strLowerLimitValue = lowerLimits;
var strUpperLimitValue = upperLimits;
string strAreaValue = areas;
string strProductivityValue = productivities;
string strFobValue = fobs.ToString();
var libraryLocation = "C:/Users/" + userName + "/Documents/R/win-library/3.2";
string rPath = #"C:\Program Files\R\R-3.3.2\bin\x64";
string rHome = #"C:\Program Files\R\R-3.3.2";
//Initialize REngine
REngine.SetEnvironmentVariables(rPath, rHome);
REngine engine = REngine.GetInstance();
engine.Initialize();
if (fobs.Length > 1)
{
strFobValue = string.Join(" ", fobs);
}
else
{
strFobValue = "ALL";
}
//Declare R Script path
var rScriptPath = "C:/Users/" + userName + "/Documents/R/RWDir/Loop_Optimization.R";
//Check to see if there was more than one location selected
if (strLocationValue.Length > 1)
{
foreach (var item in strLocationValue)
{
//Set string location to each location value in loop
var strlocation = item;
//Add values to parameter list
var myParams = new List<string>
{
strModelTypeValue,
strFileName,
strlocation,
strLowerLimitValue,
strUpperLimitValue,
strAreaValue,
strProductivityValue,
strFobValue,
libraryLocation
};
//Set myParams as arguments to be sent to r script
engine.SetCommandLineArguments(myParams.ToArray());
engine.Evaluate("source('" + rScriptPath + "')");
}
}
//Only one location specified, no need to loop
else
{
foreach (var item in strLocationValue)
{
//Set string location to each location value in loop
var strlocation = item;
var myParams = new List<string>
{
strModelTypeValue,
strFileName,
strlocation,
strLowerLimitValue,
strUpperLimitValue,
strAreaValue,
strProductivityValue,
strFobValue,
libraryLocation
};
engine.SetCommandLineArguments(myParams.ToArray());
engine.Evaluate("source('" + rScriptPath + "')");
}
}
//engine.Evaluate("source('" + rScriptPath + "')");
//engine.Dispose();
return Json("success", JsonRequestBehavior.AllowGet);
}
have you done any debugging by attaching process .

language option in reCAPTCHA ASP.NET plugin

I'm using ASP.NET plugin for reCAPTCHA in my ASP.NET MVC application. Recaptcha assembly version is 1.0.4.0. Is there a way to set language to be used for RecaptchaControl?
var captchaControl = new Recaptcha.RecaptchaControl
{
ID = "recaptcha",
Theme = "blackglass",
PublicKey = "public_key",
PrivateKey = "private_key"
};
This feature was not supported in v1.0.4.0. Please download the latest version and try again.
http://code.google.com/p/recaptcha/downloads/detail?name=recaptcha-dotnet-1.0.5.0-binary.zip
with the help of this article here is how I've done it. the key is editing the generated html at the end; replacing "RecaptchaOptions = {" with "RecaptchaOptions = { lang : 'supported_language_code',"
public static string GenerateCaptcha(this HtmlHelper helper)
{
var captchaControl = new Recaptcha.RecaptchaControl
{
ID = "recaptcha",
Theme = "clean",
PublicKey = "public_key_here",
PrivateKey = "private_key_here"
};
var htmlWriter = new HtmlTextWriter(new StringWriter());
captchaControl.RenderControl(htmlWriter);
var html = htmlWriter.InnerWriter.ToString();
html = html.Replace("RecaptchaOptions = {", "RecaptchaOptions = { lang : 'tr', ");
return html;
}
EDIT: A cleaner solution is given here. (System.Web.Helpers)

How to retrieve all key-value pairs in a resource file located in App_GlobalResources

In my ASP.NET MVC application, I manage localized texts in .resx files located in App_GlobalResources folder. I am able to retrieve any text value in any file knowing its key.
Now, I want to retrieve all key/value pairs in a particular resource file in order to write the result to some JavaScript. A search revealed that I might be able to use ResXResourceReader class and iterate through the pairs; however the class is unfortunately located in the System.Windows.Forms.dll and I don't want to wire that dependency to my web app. Is there any other way I can implement this feature?
I've found the solution. Now no need to reference Forms.dll.
public class ScriptController : BaseController
{
private static readonly ResourceSet ResourceSet =
Resources.Controllers.Script.ResourceManager.GetResourceSet(CurrentCulture, true, true);
public ActionResult GetResources()
{
var builder = new StringBuilder();
builder.Append("var LocalizedStrings = {");
foreach (DictionaryEntry entry in ResourceSet)
{
builder.AppendFormat("{0}: \"{1}\",", entry.Key, entry.Value);
}
builder.Append("};");
Response.ContentType = "application/x-javascript";
Response.ContentEncoding = Encoding.UTF8;
return Content(builder.ToString());
}
}
Okay, no other answer. Seems like referencing Forms.dll is the only way right now. Here's the code I came up with.
public class ScriptController : BaseController
{
private const string ResxPathTemplate = "~/App_GlobalResources/script{0}.resx";
public ActionResult GetResources()
{
var resxPath = Server.MapPath(string.Format(ResxPathTemplate, string.Empty));
var resxPathLocalized = Server.MapPath(string.Format(ResxPathTemplate,
"." + CurrentCulture));
var pathToUse = System.IO.File.Exists(resxPathLocalized)
? resxPathLocalized
: resxPath;
var builder = new StringBuilder();
using (var rsxr = new ResXResourceReader(pathToUse))
{
builder.Append("var resources = {");
foreach (DictionaryEntry entry in rsxr)
{
builder.AppendFormat("{0}: \"{1}\",", entry.Key, entry.Value);
}
builder.Append("};");
}
Response.ContentType = "application/x-javascript";
Response.ContentEncoding = Encoding.UTF8;
return Content(builder.ToString());
}
}

Resources