Server side data conversions - console

I have created an console app and deployed it in the server. Running via Task Scheduler.
I have tested this code on my machine:
string qty = "-3.00"
decimal itemQty = 0;
itemQty = Math.Abs(Convert.ToDecimal(qty));
Returns: 3.00
However, upon deployment to server, the same code
Returns: 300.00
Why is that?
I know for dates I can do System.Globalization.CultureInfo.InvariantCulture
Can I develop a workaround for this?

Added CultureInfo for Convert.ToDecimal
itemQty = Math.Abs(Convert.ToDecimal(qty, CultureInfo.InvariantCulture));

Related

Zebra Print issue using asp.net with c#

I am using the PrintDocument for printing directly to the network printer using asp.net with and C#. The application hosted in IIS with Windows authentication. I am not getting the error and also the PrintStatus is Printing. But we can not see the printed document in the printer and also there is no errors in the printer.
System.Drawing.Printing.PrintDocument printdoc = new System.Drawing.Printing.PrintDocument();
printdoc.DefaultPageSettings.PaperSize = new PaperSize("Custom", 4, 3);
printdoc.OriginAtMargins = true;
// Set the printer name
PrinterSettings printer = new PrinterSettings();
printer.PrinterName = SqlDatabaseUtility.GetZebraPrinterName();
string fullName = CheckPrinterConfiguration(printer.PrinterName);
if (!String.IsNullOrEmpty(fullName))
{
printdoc.PrinterSettings.PrinterName = fullName;
// Handle printing
if (printdoc.PrinterSettings.IsValid)
{
printdoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printdoc_PrintPage);
printdoc.PrinterSettings.Copies = 2;
printdoc.Print();
}
}
Just a theory, but the PrintDocument class is a descendant of Component and so implements IDisposable.
In the same way that you don't leave SqlConnection instances undisposed, you should call Dispose() on your printdoc instance so that any unmanaged resources held by the PrintDocument instance - such as a handle to the printer device, perhaps - get released.
Put a using clause around your printing block as below. It might help with your problem, but even if it does not it is proper practice.
using (System.Drawing.Printing.PrintDocument printdoc = new System.Drawing.Printing.PrintDocument())
{
...
}
The next line of enquiry would be to follow up on the "user permissions" suggestion in the comment. Assuming that your code works if you run it in a test console application, a quick test for this would be to change the user account of your web app's Application Pool to be your own account. If your web app starts printing, then you know that permissions are the problem.

Angular SPA cannot open remote SSRS report

thanks to all for your time and efforts trying to help me solve this.
Now lets get to it... I have an AngularJS SPA. I would like to provide links on my view page, that when clicked, open a new tab and launch pre-existing SSRS reports in PDF format. Technically what I am trying to do: Render an SSRS report in my Repository, pass that through my WEB API then on to my SPA for display in a new tab.
One important note before I go any further: This setup, method, approach works flawlessly on my local machine within Visual Studio. It's when I move my SPA to a remote Web server (the same server that hosts SSRS) that I have a problem.
My Landscape:
Local Development Machine (Windows 7 Pro, VS2015 Pro)
Server1 (Win Server 2012R2): Hosts IIS (8), SPA, SQL (2014) and SSRS
Server2 (Win Server 2012R2). Hosts SSRS (SQL 2012) source of data (happens to be SSAS cubes, but I don't think that matters).
On My Local Development Machine:
As stated above the solution works fine through Visual Studio. The only part of the solution on my local machine is the SPA. The SSRS and SQL portion are located remotely. I can launch my SPA, click on a link and new tab opens containing the PDF report. I can also make a call directly to the web API and display a PDF report (http://localhost:3040/api/dataservice/ProductivityReportH/)
Problem 1
Browsing to the deployed version of my SPA on Server1, the application displays fine. But, if I click on a report hyperlink I get a the following message:
Do you want to open or save ProductivityReportH/ (3.28KB) from Server1?
No matter what I click (Open, Save, Cancel) nothing happens.
If I try and launch the report directly through the API, I get the same message. There are no errors displayed in the console window. I could find no errors in the Server1 log files.
On Server1: I can display the report via the SSRS report viewer.
Problem 1A
Using a browser on Server1, I can display the application just fine. But, if I click on a report hyperlink I get the same message as Problem 1. If I try to launch the report directly through the web API (http://Server1/projecttracker/api/dataservice/ProductivityReportH/)
on Server1, I get the same message.
Any ideas would be greatly appreciated
My SPA Setup:
View Page:
<div class="view indent">
<div class="container">
<h2>Productivity Reports Method 1</h2>
<a ng-href='#here' ng-click="hproductivityreport()">Launch</a><br>
</div>
My Controller:
(function () {
var ProjectsController = function ($scope, $window) {
$scope.hproductivityreport = function () {
$window.open('api/dataservice/ProductivityReportH/', '_blank');
};
}
ProjectsController.$inject = ['$scope', '$window'];
angular.module('ReportTracker').controller('ProjectsController', ProjectsController)
}());
The WEB API:
using ProjectTracker.Repository;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
namespace ProjectTracker.Model
{
[Authorize]
public class DataServiceController : ApiController
{
IProjectTracker _ProjectTrackerRepository;
public DataServiceController()
: this(null)
{
}
public DataServiceController(IProjectTracker Repo)
{
_ProjectTrackerRepository = Repo ?? new ProjectTrackerRepository ();
}
[HttpGet]
public HttpResponseMessage ProductivityReportH()
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
byte[] bytes = _ProjectTrackerRepository.RenderProductivityReport("Hibble, Norman");
Stream stream = new MemoryStream(bytes);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
}
}
The Respository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
namespace ProjectTracker.Repository
{
public class ProjectTrackerRepository : RepositoryBase<ProjectTrackerContext>, IProjectTracker
{
ProjectTrackerContext _Context;
public ProjectTrackerRepository()
{
_Context = new ProjectTrackerContext();
}
public Byte[] RenderProductivityReport(string _sManager)
{
Server1.ReportExecutionService rs = new Server1.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://Server1/reportserver/ReportExecution2005.asmx";
// Render arguments
byte[] result = null;
string reportPath = "/Staff Client Services/StaffProductivity";
string format = "PDF";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
//Create the list of parameters that will be passed to the report
List<Server1.ParameterValue> lstParameterValues = new List<Server1.ParameterValue>();
Server1.ParameterValue aParameter = new Server1.ParameterValue();
aParameter.Name = "SupervisorSupervisorName";
aParameter.Value = "[Supervisor].[Supervisor Name].&[" + _sManager + "]";
lstParameterValues.Add(aParameter);
Server1.ParameterValue bParameter = new Server1.ParameterValue();
bParameter.Name = "PayPeriodPayPeriodYear";
bParameter.Value = "[Pay Period].[Pay Period Year].&[2015]";
lstParameterValues.Add(bParameter);
int index = 0;
Server1.ParameterValue[] parameterValues = new Server1.ParameterValue[lstParameterValues.Count];
foreach (Server1.ParameterValue parameterValue in lstParameterValues)
{
parameterValues[index] = parameterValue;
index++;
}
string encoding;
string mimeType;
string extension;
Server1.Warning[] warnings = null;
string[] streamIDs = null;
Server1.ExecutionInfo execInfo = new Server1.ExecutionInfo();
Server1.ExecutionHeader execHeader = new Server1.ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, historyID);
rs.SetExecutionParameters(parameterValues, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (Exception e)
{
Exception Errr = e.InnerException;
}
return result;
}
}
}
Finally! For those that are interested...
Found this from nearly two years ago.
AppPool Permission Issue with Accessing Report Server
In particular the comment below:
Almost the same situation here except IIS and Report Server running on Windows Server 2008 R2. I used to have the asp.net application running with it's own application pool and everything worked. When I changed the application to the DefaultAppPool (due to a different problem), I got the permissions problem. I changed the Identity of the DefaultAppPool from ApplicationPoolIdentity to LocalSystem (in IIS, Advanced Settings) and it worked again.
Changed web server default app pool to LocalSystem and wha-la, I am rendering PDF reports from an SSAS cube through my AngularJS SPA.

How to recognize client's computer?

I have a problem recognizing client's computer data. I'm developing an application that requires some king of recongnision of machine client is currently using. I tried
System.Environment.MachineName;
and also
string hostName = Dns.GetHostName();
var add = Dns.GetHostAddresses(hostName);
, but it always returns data of server computer IIS is working on. Also i tried to get processors and basebords id's but with same result as previous examples.
ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_BaseBoard");
ManagementObjectCollection moc = mos.Get();
foreach (ManagementObject mo in moc)
{
serial = mo["SerialNumber"].ToString();
}
ManagementObjectSearcher mbs = new ManagementObjectSearcher("Select * From Win32_processor");
ManagementObjectCollection mbsList = mbs.Get();
string id = "";
foreach (ManagementObject mo in mbsList)
{
id = mo["ProcessorID"].ToString();
}t
System will be used inside a private network(not to be used publicly).
Is there any way to somehow recognize any unique client's computer data in ASP.NET web application development, or .NET simply deny any recognision of client's computer data due to safety?
Thanks
Since the code runs on the Server, "System" is the Server. In ASP.NET you can get information about who is requesting (the client) with the Request object. Try this:
Request.UserHostAddress
Or this:
Request.UserHostName

Cannot acces users Active Directory password information on production server

I'm developing an MVC application and I have a routine that gets the currently logged on users password info and it works fine on my PC but when I publish my application to a live server on the domain, I don't seem to be able to gain access to the AD information. I have used very similar code in a currently running asp.net web application and it works just fine. I compared security settings on both applications and they look identical. Here is the routine:
public int GetPasswordExpiration()
{
PrincipalContext domain = new PrincipalContext(ContextType.Domain);
string currUserName = WindowsIdentity.GetCurrent().Name;
UserPrincipal currLogin = UserPrincipal.FindByIdentity(domain, currUserName);
DateTime passwordLastSet = currLogin.LastPasswordSet.Value; //here is where it chokes***
int doyPasswordSet = passwordLastSet.DayOfYear;
int doy = DateTime.Today.DayOfYear;
int daysSinceLastset = (doy - doyPasswordSet);
int daysTilDue = (120 - daysSinceLastset);
return (daysTilDue);
}
I am an administrator on the domain so I think I have an application permissions issue, but since the failing application has the same permissions as the working application, I'm not sure where to look next. Any help is appreciated.
I'm answernig my own question because I want to post the code that works. Wiktor Zychla nailed it when asking if WindowsIdentity.GetCurrent().Name applied to the identity of the application pool rather than the logged in user. As a matter of fact it did, thanks Wiktor!
Here is the modified code that works. I did change the way I got the users identity (explained why below).
Controller Code:
using MyProject.Utilities; // Folder where I created the CommonFunctions.cs Class
var cf = new CommonFunctions();
string user = User.Identity.Name;
ViewBag.PasswordExpires = cf.GetPasswordExpiration(user);
Code in CommonFunctions
public int GetPasswordExpiration(string user)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal currLogin = UserPrincipal.FindByIdentity(ctx, user);
DateTime passwordLastSet = currLogin.LastPasswordSet.Value;
int doyPasswordSet = passwordLastSet.DayOfYear;
int doy = DateTime.Today.DayOfYear;
int daysSinceLastset = (doy - doyPasswordSet);
int daysTilDue = (120 - daysSinceLastset);
return (daysTilDue);
}
The one thing that clued me in was that I decided to just run all the code in my controller and when I did, I got a red squiggly saying "The name WindowsIdentity does not exist in this context":
string currUserName = WindowsIdentity.GetCurrent().Name;
Also, the reason I retrieved User.Identity.Name in the Controller and passed it to the function is because once I got things working and wanted to thin out my controller, I tried to get User.Identity.Name in the function but I got another red squiggly with the same message under User in this line:
string user = User.Identity.Name;
So I figure this is a .net thing and just went with getting the User.Identiy.Name in the controller, pass it to the function and all is well. This one really tested my patience and I hope this post can help someone else.

Use WMI to create IIS Application Directory with C#

We have a web application that is installed on Windows 2003 and Windows 2008 systems. In the past, our install code used ADSI to create a couple of application directories in IIS, but this requires the IIS 6 management components to be installed in Windows 2008. I have been trying to use WMI to create the application directories so we can support both operating systems.
I have been trying this code
public static void AddVirtualFolder(string serverName, string websiteId, string name, string path)
{
ManagementScope scope = new ManagementScope(string.Format(#"\\{0}\root\MicrosoftIISV2", serverName));
scope.Connect();
string siteName = string.Format("W3SVC/{0}/Root/{1}", websiteId, name);
ManagementClass mc = new ManagementClass(scope, new ManagementPath("IIsWebVirtualDirSetting"), null);
ManagementObject oWebVirtDir = mc.CreateInstance();
oWebVirtDir.Properties["Name"].Value = siteName;
oWebVirtDir.Properties["Path"].Value = path;
oWebVirtDir.Properties["AuthFlags"].Value = 5; // Integrated Windows Auth.
oWebVirtDir.Properties["EnableDefaultDoc"].Value = true;
// date, time, size, extension, longdate ;
oWebVirtDir.Properties["DirBrowseFlags"].Value = 0x4000003E;
oWebVirtDir.Properties["AccessFlags"].Value = 513; // read script
oWebVirtDir.Put();
ManagementObject mo = new ManagementObject(scope, new System.Management.ManagementPath("IIsWebVirtualDir='" + siteName + "'"), null);
ManagementBaseObject inputParameters = mo.GetMethodParameters("AppCreate2");
inputParameters["AppMode"] = 2;
mo.InvokeMethod("AppCreate2", inputParameters, null);
mo = new ManagementObject(scope, new System.Management.ManagementPath("IIsWebVirtualDirSetting='" + siteName + "'"), null);
mo.Properties["AppFriendlyName"].Value = name;
mo.Put();
}
}
However, I get path not found errors on known directories. If anybody has some references I can use, I would greatly appreciate it. Any other suggestions on how to go about this are also welcome.
Using the code above, you will still need the IIS6 compatibility bits on Windows 2008/IIS7. The reason for this is that the calls to set properties such as DirBrowseFlags, AccessFlags and so on are IIS 6 metabase properties that are not supported in IIS7 without the IIS6 management components.
For IIS7 I'd recommend programming directly against the Microsoft.Web.Administration namespace, but if you really need to use WMI then see this article:
Managing Sites with IIS 7.0's WMI Provider (IIS.NET)

Resources