Cassia method works fine in console app but error in asp.net app - cassia

I am running this code.
server.Open();
//Console.WriteLine("----------------------------------------------------");
//Console.WriteLine("Active users on {0}", machineName);
foreach (ITerminalServicesSession session in server.GetSessions())
{
System.Security.Principal.NTAccount account = session.UserAccount;
if (account != null)
{
if (session.ConnectionState == Cassia.ConnectionState.Active)
{
((TextBox)Page.FindControl("txt" + machineName.Substring(7))).Text += session.UserName + " idle " + session.IdleTime.TotalMinutes + " minutes" + "\r\n";
}
}
}
It runs fine in console application but gives "No more data is available " error in asp.net page.

I created a new Application Pool in IIS 7 and set its identity as my personal username instead of the default AppIdenitity. Then I assigned this new Application Pool to my ASP.NET web application in IIS. Issue fixed.

Related

Cassia: Win32Exception no more data available

I'm using Cassia to get the sessions of two servers.
- Windows 2003 R2 Terminal Server
- Windows 2008 R2 Server
The second one, which is not a terminal server works fine. However the first one is getting some issues.
The error message is:
System.ComponentModel.Win32Exception: No more data is available
at Cassia.Impl.NativeMethodsHelper.GetSessionInfos(ITerminalServerHandle server)
at Cassia.Impl.TerminalServer.GetSessions()
at Server_Sessions.Program.Main(String[] args)
Can anyone help with this error message and what to do?
The code I found so far for testing purposes:
ITerminalServicesManager manager = new TerminalServicesManager();
using (ITerminalServer server = manager.GetRemoteServer("server"))
{
server.Open();
foreach (ITerminalServicesSession session in server.GetSessions())
{
Console.WriteLine("Session ID: " + session.SessionId);
Console.WriteLine("User: " + session.UserAccount);
}
}
After trying a few things I found my mistake. Code is tested and working. I needed to use Impersonation, because my user account is not working on the server. So I impersonate as the standard user on this server and you'll get the relevant information.
using(Impersonation.LogonUser(domain, user, password, LogonType.NewCredentials))
{
ITerminalServicesManager manager = new TerminalServicesManager();
using (ITerminalServer server = manager.GetRemoteServer(server))
{
server.Open();
foreach (ITerminalServicesSession session in server.GetSessions())
{
//Do your stuff here.
}
}
}

Calling into my own DLL when depolyed on Azure

I have a simple Windows Azure cloud service that does random number generation running on my local machine. I have then published this to azure
public string GetNumber()
{
Random number = new Random();
return "number = " + number.Next(1, 100).ToString() + " number ";
}
When I call this method from my client everything works fine.
ie
ServiceReference1.RandomNumbersClient client = new ServiceReference1.RandomNumbersClient();
Console.WriteLine("Starting .... ");
Console.WriteLine(client.GetNumber());
Now, the next step is I have added some code that requires "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5.2\System.Speech.dll" to be available in the project. This is easy on my local server as I just add the reference to the dll in my VS project.
New method ....
public string GetNumberAsString()
{
Random number = new Random();
SpeechSynthesizer synth = new SpeechSynthesizer();
synth.SetOutputToDefaultAudioDevice();
synth.Speak("This example demonstrates a basic use of Speech Synthesizer");
return "number = " + number.Next(1, 100).ToString() + " number ";
}
Problem now is when I publish to Azure. How do I make the DLL available to my app running in Azure?
When I call the GetNumber() method it works fine but any call to GetNumberAsString() fails because of the additional code.
ServiceReference1.RandomNumbersClient client = new ServiceReference1.RandomNumbersClient();
Console.WriteLine("Starting .... ");
Console.WriteLine(client.GetNumberAsString());
How do I actually inspect the logs for the Webservice running on Azure so I can make a start at finding out what the problem is.

Why won't my ASP.NET application export CSV when hosted as an Azure Web app?

MY application exports CSV's fine when I test it from Visual Studio, but when I deploy it to an Azure as a Web app, instead of exporting a CSV I get a Error code: ERR_INVALID_RESPONSE.
Below is the method I use :
public void ExportEmpReport(int? er_id)
{
var er_hdr = db.expense_report_hdr.Include(w => w.employeeExpUser).Where(x => x.ID == er_id).FirstOrDefault();
StringWriter sw = new StringWriter();
sw.WriteLine("Employee Name: " + er_hdr.employeeExpUser.fullname + ", Period: " + er_hdr.period + ", Expense Report ID: " + er_id);
sw.WriteLine("Date of Expense , Expense Class , Detail , Cust/Conv , Notes , Amount , GL Code , Project Code");
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=ExpenseReport_" + er_id + ".csv");
Response.ContentType = "text/csv";
var lines = db.expense_report_line.Where(y => y.er_id == er_id);
foreach (var line in lines)
{
string exp_class = line.expenseType.expense.ToString().Replace(",", "");
string detail = (line.expense_detail != null) ? line.expense_detail.Replace(",", "") : "";
string cust_conv = (line.cust_conv != null) ? line.cust_conv.Replace(",", "") : "";
string notes = (line.notes != null) ? line.notes.Replace(",", "") : "";
sw.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", line.expense_date, exp_class, detail, cust_conv, notes, line.amount, line.gl_code.GL_code, line.project_code));
}
Response.Write(sw.ToString());
Response.End();
}
Here are some suggestions you may use to try and troubleshoot it:
A. Debug the web app locally, while connected to the DB on Azure. Are the tables being read correctly?
If the code fails to read the data from the database, make sure that the database is updated to the latest schema.
B. If it reads the data correctly, debug it step by step, and watch exactly where it fails.
If it fails at a particular line, remove/replace some lines of code until the local web app is running correctly against the DB on Azure. You may be able to identify the offending line(s) of code, and then report back here to allow others to help you troubleshoot further.
C. Once you get it working with the local app against the DB on Azure, deploy the updated project code to the Web App on Azure to see if it still runs correctly.
If it still doesn't work, maybe there's a setting on your Web App that is preventing it from running the code successfully.
D. Check the version of the .NET Framework on the Web App in Azure. The choices should be v3.5 or v4.6 (for non-Core 1.0 applications).
If it has the wrong version selected, make sure you select the correct version.
E. Enable Remote Debugging of the Web App running on Azure.
There's a Remote Debugging feature that you can toggle on/off in the Application Settings blade, where you can also select the VS version (2012, 2013, 2015). Turn it on to pinpoint which line of code it's failing at.

Port 9553 (from Firebase) blocked by webhost, can't find a way to successfully cURL over alternate port

I'm using PHP and cURL with the REST api, and even though I can cURL the initial Nest Developer api endpoint, once it redirects to Firebase's url it's over port 9553, which my webhost has blocked (no chance to get opened up either). The connection times out and throws the 'could not connect to host' error.
My code is working fine, I can run it on my local server with no problems.
I'm new at using cURL, what are my options? It seems to me that the problem is the port Firebase is insisting on using. I can cURL a number of different locations, over :80 and :443 without problem, just not Firebase's url. Will I need to run through a proxy in order to access the data?
Or, is this something that might be solved by using Firebase's PHP library? I'm not super interested in using it if I don't have to, cURL would do the job nicely, and I don't know really know how it works.
There is no way to get around the redirects with REST, they point to specific ports and hosts in Nest's cloud.
What is wrong with Firebase's Web Sockets client? It is more performant than REST.
joshguerette,
Is your firewall blocking that port?
You can open the port from your c# code with this:
using Microsoft.TeamFoundation.Common;
private void AddPortToFirewall(int portNumber, string name)
{
INetFwMgr icfMgr = null;
try
{
Type TicfMgr = Type.GetTypeFromProgID("HNetCfg.FwMgr");
icfMgr = (INetFwMgr)Activator.CreateInstance(TicfMgr);
}
catch (Exception ex)
{
Debug.WriteLine("Failed in AddPortToFirewall.Activator " + portNumber.ToString() + " " + name + " " + ex.ToString());
return;
}
try
{
INetFwProfile profile;
INetFwOpenPort portClass;
Type TportClass = Type.GetTypeFromProgID("HNetCfg.FWOpenPort");
portClass = (INetFwOpenPort)Activator.CreateInstance(TportClass);
// Get the current profile
profile = icfMgr.LocalPolicy.CurrentProfile;
// Set firewall enabled
if (!profile.FirewallEnabled)
profile.FirewallEnabled = true;
// Set the port properties
portClass.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
portClass.Enabled = true;
portClass.Name = name;
portClass.Port = portNumber;
portClass.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
// Add the port to the ICF Permissions List
bool portExisted = false;
foreach (INetFwOpenPort p in profile.GloballyOpenPorts)
{
if (p.Port == portNumber && p.Name == name)
{
portExisted = true;
Debug.WriteLine("Windows Firewall inbound list:" + p.Port + " " + p.Name);
break;
}
}
if (!portExisted)
{
profile.GloballyOpenPorts.Add(portClass);
Debug.WriteLine("ServicePort " + portNumber.ToString() + " " + name + " was added into Windows Firewall inbound list.");
}
else
{
Debug.WriteLine("ServicePort " + portNumber.ToString() + " " + name + " has already in Windows Firewall inbound list.");
}
}
catch (Exception ex)
{
Debug.WriteLine("Failed in AddPortToFirewall " + portNumber.ToString() + " " + name + " " + ex.ToString());
}
}

C# LDAP SetPassword throws The RPC server is unavailable

I am trying to create a new user -> set password and enable account .
earlier i was using 1 single object , but after looking at a few posts i decided to use 'using' for 3 different operations
string strDisplayName = txtFirstName.Text + " " + txtLastName.Text;
string strUser = txtLoginName.Text;
string pw = "pass#123";
using (var objADAM = new DirectoryEntry("LDAP://" + adlink + "/CN=Users,DC=SS,DC=COM", "ss\\luser", "pass#123", AuthenticationTypes.Secure))
{
const long ADS_OPTION_PASSWORD_PORTNUMBER = 6;
const long ADS_OPTION_PASSWORD_METHOD = 7;
const int ADS_PASSWORD_ENCODE_CLEAR = 1;
string strPort = "389";
int intPort = Int32.Parse(strPort);
using (var objUser = objADAM.Children.Add("CN=" + strUser, "user"))
{
objUser.Properties["sAMAccountName"].Add(strUser);
objUser.CommitChanges();
}
}
using (var user = new DirectoryEntry("LDAP://" + adlink + "/CN=" + strUser + ",CN=Users,DC=SS,DC=COM", "ss\\rluser", "pass#123"))
{
user.Invoke("SetPassword", new object[] { "password" });
user.CommitChanges();
}
using (var user = new DirectoryEntry("LDAP://" + adlink + "/CN=" + strUser + ",CN=Users,DC=SS,DC=COM", "ss\\rluser", "pass#123"))
{
//Enable account and change password on first logon flag
user.Properties["userAccountControl"].Value = 0x200;
user.Properties["pwdLastSet"].Value = 0;
user.CommitChanges();
}
I must mention, that i am outside the domian, and trying to connect to a remote AD on another domain . The credential's passed however are the ADMIN
The user creation goes on smoothly (after some hiccups with port opening & LDAP connections) , but the issue occurs when the invoke ->setpassword is called .
The error is :"the RPC server is unavailable " , just to make sure i am not doing something wrong in my code, i downloaded a LDAP admin tool and tried to reset the password of an existing user ->same error
steps
-checked the RPC service running
-opened RPC ports -135 ,blah blah..basically every port there is to open :|
any help is appreciated .
Thanks
Rajat
For example:
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://dnsname.domain.com:389/OU=Companies;
Microsoft recommends accessing using DNS.
if the machine you are accessing is connected to a different domain, you must specify it as "ip dnsname" in the hosts file in the "C:\Windows\System32\drivers\etc " directory.
using adlink is string domain, because AD method Invoke using domain name: "abc.com"

Resources