Friday, February 10, 2017

First time connecting to Azure with Powershell - error

While I was following Microsoft's tutorial for connecting to Azure via Powershell I got an error message when trying to run this command: Login-AzureRmAccount


The error message was:


Login-AzureRmAccount : The 'Login-AzureRmAccount' command was found in the module 'AzureRM.Profile', but the module could not be loaded. For more information, run 'Import-Module AzureRM.Profile'. At line:1 char:1
+ Login-AzureRmAccount
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Login-AzureRmAccount:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CouldNotAutoloadMatchingModule




In order to fix this issue I had to follow these steps:
  1. Open command prompt (cmd) as administrator
  2. type powershell Set-ExecutionPolicy RemoteSigned and press Enter
After this, the Login-AzureRmAccount command worked normally.

According to Microsoft, the Set-ExecutionPolicy command does the following (source):

The Set-ExecutionPolicy cmdlet enables you to determine which Windows PowerShell scripts (if any) will be allowed to run on your computer. Windows PowerShell has four different execution policies: 
Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
AllSigned - Only scripts signed by a trusted publisher can be run.
RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
Unrestricted - No restrictions; all Windows PowerShell scripts can be run.

Saturday, August 20, 2016

Installing NodeJs on a Linux Mint OS

I had to run a project in Visual Studio Code on a Linux machine (Mint) that needed NodeJs installed so I tried to follow the steps on the official page.

I realized, after some errors, that I was actually missing some things.

On the official page, the commands for the install are listed like this:

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs

Before you can run this (successfully) you also need to install curl: sudo apt-get install curl

Apparently, curl, is a client tool used to get files over different kind of protocols, like http(s) and ftp without too much interaction. The legend goes that it can also support authentication (I'm kidding, it isn't a legend, it's true, check the official page) :).

Another thing that baffled me was the last "-" at the end of the first line. Because of it I thought there was just one command so I copied them both and tried to run them... with no success.

So, first take the first line:
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -

and when it is done, run the next command:
sudo apt-get install -y nodejs

After this you can check what version was installed with the command node -v. When you install Node you also get npm, which is the package manager for npm, basically where all the goodies come from.

Adding Node to PATH

After the installation is complete it is necessary that we add Node to PATH so that all the packages will be installed in that location. The first thing to do is to create a folder named npm in the home folder.

Open .bashrc file with a text editor. This file is also in the Home folder, but it is hidden. Right-click show hidden files.

Add at the end of the file: export PATH="$HOME/npm/bin/:$PATH".

If the terminal window is open, close it and open it again, then type echo $PATH and you should see the path to npm/bin listed.


Monday, July 4, 2016

Running the Angular 2 Quickstart tutorial in Visual Studio Code on Mac OS

In this post I will go through the steps that I took in order to complete the Angular 2 Quickstart tutorial (with Typescript) using Visual Studio Code on Mac OS. The versions for the software are as follows:

  • VS Code: 1.2.1
  • Mac OS: 10.11.5 (El Capitan)
The Angular 2 quickstart can be found at this link: https://angular.io/docs/ts/latest/quickstart.html.

We start by creating a new solution, which in VS Code is opening a folder. In the tutorial they named the folder angular2-quickstart. It doesn't really matter, so just make a new folder.

After this we need to follow the next few steps in order to have the solution up and running in VS Code.

1. Compiling the Typescript code to Javascript.

Open Command Palette with ⇧⌘P (or View -> Command Palette) and start typing Configure Task Runner.
Then, select Tasks: Configure Task Runner and you will get the next list:

From here you need to select TypeScript - tsconfig.json. This will create a tsconfig.json under the .vscode folder.


2. Installing NodeJs and npm (if you don't already have it).

This tutorial states that you need to have at least version 5.x.x for NodeJs and 3.x.x for npm. To check if you have the required version, open a terminal window (or the Integrated Terminal in VS Code) and type node -v for NodeJs and npm -v for npm.

From here on I have followed the steps in the tutorial. 

In order to be able to run the application from VS Code a few additional steps are required:

1. Click on the Debug icon on the left side.

2. Click on the cog icon and select NodeJs from the list. This will create a file called launch.json under the .vscode folder.
Note: if you click the cog icon again, nothing will happen. If you want to see the available options again, delete the launch.json file.

3. In the launch.json file, edit the program property so that it looks like this: ${workspaceRoot}/node_modules/lite-server/bin/lite-server

4. Click on the start icon and the application should start.

Wednesday, August 26, 2015

Integrating Swift with Objective C

I started to implement the new design for Jano (Japano) and I decided to do some small refactoring of the code.

In the Achievements screen I am displaying a list of levels that the user can achieve by taking tests in a UIScrollView. It's a maximum of 4 levels and each of the views needs to have a background image.

Initially I subclassed UITableViewCell and I wrote the code inside the class for the arranging of the GUI elements.
Now I want to use another class that will take care of the GUI only. I will do this using Swift and in this post I will write about how to combine the two types of files.

First thing, add a new file from the menu File - New - File and select Swift File. After naming it, Xcode will ask you if you want to add bridging header. Click Yes.

I have named the class LevelCellInterfaceTool. By default the class is not public, so I had to modify the access level of the class to public:


public class LevelsCellInterfaceTool: NSObject {

}
Inside the class I then created a public method (func) that just shows a simple UIAlertView:

public class LevelsCellInterfaceTool: NSObject {
public func ShowSimpleMessage()
    {
        let message = "This is a UIAlerView declared in Swift!"
        let v = UIAlertView(title: "Swift UIAlertView", message: message, delegate: nil, cancelButtonTitle: "Ok")
        v.show()
    }

}
The next challenge was to call ShowSimpleMessage from a class declared in an Objective C file (.h and .m). This was accomplished in 3 simple steps:

1. Forward declare LevelCellInterfaceTool in the interface file (.h) of the class that needs it: 
@class LevelsCellInterfaceTool;

@interface LevelsListCellTableViewCell : UITableViewCell

{
        
}

@end

2. In the implementation file (.m) use an #import directive for all the classes declared with Swift. In the official documentation it is saying to use a particular naming convention: ProductModuleName-Swfit.h.
In my case, ProductModuleName is the name of the project. So, it becomes Jano-Swift.h:

#import "LevelsListCellTableViewCell.h"
#import "Jano-Swift.h"

@implementation LevelsListCellTableViewCell
...
@end

3. Calling the method.
After writing a new method (func) in the Swift class it is necessary to first build the project so that the Objective-C class sees it (at least in Xcode 6.3.2).
Somewhere in the class instantiate the Swift class as you would with a regular Objective-C class:

LevelsCellInterfaceTool *guiTool = [[LevelsCellInterfaceTool alloc] init];
        [guiTool ShowMessage];
        [guiTool release];

Wednesday, September 17, 2014

How to install a Windows service from the command prompt

Installing a Windows service from the command prompt is a fairly simple task, only a few steps to follow.


  1. Build the project in Release mode
  2. Go to the Release folder and copy the full address from the address bar
  3. Open Visual Studio Command Prompt (On Windows 7 you can find it under Start - All programs - Visual Studio - Visual Studio Tools; on Windows 8 click start and start typing Visual Studio Command Prompt )*
  4. Install the service using the command installUtil and passing the path you copied at step 2: installUtil pathToFolder

If the service is already installed you will need to uninstall it first:
installUtil /u pathToFolder

*If on the machine where you need to install it you don't have Visual Studio, you will have to find the executable installUtil. On my Windows 8 (but I believe it is the same on Windows 7) it is in C:\Windows\Microsoft.NET\Framework\v4.0.30319


Monday, September 8, 2014

Creating a custom setter and getter for a property in Objective C


When creating the mobile application Jano I had to show different statistics in a special menu. It had to appear in a label (of course) and I wanted to format it according to the phone's style.

The best solution for me was to add a string property to the model that would return the NSNumber property formatted accordingly.

In the .h file I defined the public properties as follows:


@property (nonatomic, strong) NSString *ValueAsString;

@property (nonatomic, strong) NSNumber *Value;


In the .m file, the code appear like this:
@synthesize Value = _value, ValueAsString = _valueAsString; 


//Getter for ValueAsString
-(NSString*) ValueAsString
{
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setGroupingSeparator:[[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator]];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *result = [formatter stringFromNumber:_value];

    return result;
}

-(void)setValueAsString:(NSString*)value
{
_valueAsString = value;
}
Although I had no use for the setter, I added it here so that it would be a full example.

Thursday, August 28, 2014

JavaScript runtime error: Unable to get property 'call' of undefined or null reference

I got this error after I had installed a NuGet package with editor templates for Bootstrap for ASP.NET MVC 5.

The solution consisted of 2 steps:
First, install package JQuery Migrate. Second, edit the method RegisterBundles in class BundleConfig from App_Start folder and change the part where it adds the bundle jqueryval.

Initially, in my project, it looked like this:

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                          "~/Scripts/jquery.validate*"
                        ));


Here you have to add a line to include the jquery-migrate files:

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery-migrate*",
                        "~/Scripts/jquery.validate*"
                        ));



Monday, July 21, 2014

Could not load file or assembly 'WebGrease, Version=1.5.1.25624, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies

I was working on a MVC 5 project in Visual Studio 2013, and I was getting the error in the title everytime I was trying to run the project. We were using Visual SVN for the versioning and I was the only one in my team that had this problem.

The only thing that worked for me was this:
  1. Uninstall Microsoft.AspNet.Web.Optimization
  2. In Nuget command prompt run: install-package Microsoft.AspNet.Web.Optimization -Version 1.0.0

This will install an older version of Web.Optimization. The project was initially referencing version 1.1.0. The problem is not with WebGrease, but with the System.Web.Optimization.dll that is referencing an old, inexisting version of WebGrease.

When I ran the project, it worked, but I wanted to use the same package version as the rest of team. So, I tried to update but... the error returned...

After this, I deleted the project (again) and took it back from the SVN. To my surprize, it started to work... The thing is that I had deleted the project completely and took it from the SVN several times before this. I even took the dlls from a colleague because I thought that maybe I'm getting corrupted files from NuGet, but to no avail.

Strange...

Thursday, July 17, 2014

UITableViewCell with UIScrollView inside

When I started coding in Objective C I had some hard times learning how to create a UITableView application. Luckily things changed over time :).

I decided to create a small sample application that shows how to add a table view to a view controller. This table view has only 2 sections, each with one custom created UITableViewCell.

The project is hosted on GitHub, here.

Structure

The AppDelegate launches the ListsTableViewController, a UIViewController that implements UITableViewDelegate and UITableViewDataSource. In the controller I have implemented only some of the methods from the protocols.

I usually use a second class to add the interface elements to my view controllers. In this case, the class is called ListsTVCInterfaceTool. It has a private property of type ListsTableViewController a method called AddTableView.

Below I have listed the code for the ListsTVCInterfaceTool.h:


#import <Foundation/Foundation.h> 
#import "ListsTableViewController.h" 

@class ListsTableViewController; 
@interface ListsTVCInterfaceTool : NSObject 

@property ListsTableViewController *controller; 

//making sure that it will be used only for the ListsTableViewController 
-(id)initWithController:(ListsTableViewController*) controller; 

//Used to add the table view to the controller 
-(void)AddTableView; 

@end
I could have added a parameter of type ListsTableViewController to the AddTableView method, but I preferred to make it a private property so that if we want to add other interface elements with different methods, we don't have to specify the same parameter everywhere. We just init the class once and pass the controller to it.

Since also the view controller will have a reference to this class I have used the @class directive to avoid a circular dependency.

The code for the ListsTVCInterfaceTool.m looks like this:

-(id)initWithController:(ListsTableViewController *)controller 

{ 

self = [super init]; 

if (self) { 

_controller = controller; 

} 

return self; 

} 



-(void)AddTableView 

{ 

CGFloat width = 0; 

CGFloat height = 0; 

width = [[UIScreen mainScreen] bounds].size.width; 

height = [[UIScreen mainScreen] bounds].size.height; 



CGRect rect = CGRectMake(0, 0, width, height); 

_controller.tableView = [[UITableView alloc] initWithFrame:rect]; 

[_controller.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]]; 

[_controller.view addSubview:_controller.tableView]; 

_controller.tableView.dataSource = _controller; 

_controller.tableView.delegate = _controller; 

[_controller.tableView setUserInteractionEnabled:YES];   



} 



Some things to notice here:

[_controller.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];

The above line will tell the table view to display only a number of rows equal to the rows in the datasource.  If this line is commented out we would see in the table view more than 2 lines, because it will try to fill the empty space with "fake" rows. I say fake, because they are there only to fill the gap between the last row from the datasource and lower bounds of the view.

_controller.tableView.dataSource = _controller; 
_controller.tableView.delegate = _controller;

The 2 lines of code will set the ListsTableViewController as the delegate and the datasource for the tableview.

Now that we saw what the interface tool class looks like, let's get back to the UITableViewController, the ListsTableViewController.

The code for the ListsTableViewController.m file is this:



- (void)viewDidLoad

{

[super viewDidLoad];



[_tableView registerClass:[AnimalListTableViewCell class] forCellReuseIdentifier:CELL_IDENTIFIER_ANIMAL];



[_tableView registerClass:[CarListTableViewCell class] forCellReuseIdentifier:CELL_IDENTIFIER_CAR];





ListsTVCInterfaceTool *interfaceTool = [[ListsTVCInterfaceTool alloc] initWithController:self];

[interfaceTool AddTableView];

}





#pragma mark - Table view data source



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

// Return the number of sections.

return 2;

}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

// Return the number of rows in the section.

return 1;

}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{



UITableViewCell *cell = nil;

if (indexPath.section == 0) {

cell = [tableView dequeueReusableCellWithIdentifier:CELL_IDENTIFIER_CAR];

}

else if (indexPath.section == 1)

{

cell = [tableView dequeueReusableCellWithIdentifier:CELL_IDENTIFIER_ANIMAL];

}



if (!cell) {

if (indexPath.section == 0) {

cell = [[CarListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_IDENTIFIER_CAR];

}

else if (indexPath.section == 1)

{

cell = [[AnimalListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_IDENTIFIER_ANIMAL];

}

}

return cell;



}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

return TABLEVIEW_CELL_HEIGHT;

}
The ViewDidLoad method registers the 2 custom cells and calls the method to add the table view to the controller.
In the cellForRowAtIndexPath method I display one cell type or the other, depending on the section I am in.

All the upper case strings here are constants defined in the Constants file.

Let's take a look at the CarListTableViewCell.m file:


@implementation CarListTableViewCell
@synthesize ScrollView = _ScrollView;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {

        // Initialization code
ListManager *manager = [[ListManager alloc] init];
models = [manager GetCars];

        [self arrangeInterface];
}

    return self;
}


#pragma mark - Interface elements

-(void)arrangeInterface
{

    CGFloat width = self.frame.size.width * [models count];
CGFloat height = TABLEVIEW_CELL_HEIGHT;

    _ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, height)];
_ScrollView.delegate = self;
_ScrollView.indicatorStyle = UIScrollViewIndicatorStyleBlack;
_ScrollView.alwaysBounceHorizontal = YES;
[_ScrollView setUserInteractionEnabled:YES];
_ScrollView.scrollEnabled = YES;
_ScrollView.pagingEnabled = YES;

    _ScrollView.contentSize = CGSizeMake(width, height);


    for (int i = 0; i < [models count]; i++) {
CarModel *model = (CarModel*)[models objectAtIndex:i];
[self GetViewFromModel:model andIndexOnScrollView:i];

    }

    [self.contentView addSubview:_ScrollView];

}


-(void)GetViewFromModel:(CarModel*)model andIndexOnScrollView:(int)index
{

    CGFloat width = self.frame.size.width;
CGFloat height = _ScrollView.frame.size.height;
CGFloat x =  width * index;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, 0, width, height)];

    NSArray *colors = [NSArray arrayWithObjects:[UIColor orangeColor], [UIColor greenColor], [UIColor blueColor],[UIColor redColor], nil];

    view.backgroundColor = (UIColor*)[colors objectAtIndex:index];

    [self AddElementsToView:view fromModel:model];
[_ScrollView addSubview: view];
}


#pragma mark - Labels

-(void)AddElementsToView:(UIView*)view fromModel:(CarModel*)model
{

    [self AddBrandLabelToView:view fromModel:model];
[self AddModelLabelToView:view fromModel:model];
[self AddYearLabelToView:view fromModel:model];

}
In the constructor I load the models array from the manager. The method to populate the array brings 3 objects of type CarModel.
Next, I arrange the interface. I first setup the UIScrollView and add to it 3 views, each with the details of the corresponding model.

The project is hosted on GitHub, here.

Monday, July 14, 2014

Access network share outside of domain from SSIS

I was trying to copy some files using SSIS to a share outside the domain, but it turned out this was not as simple as copying the files manually.

The first thing to do was to create a mapped drive using the "NET USE" command with a Execute process task:



I had to change the first 3 properties of the task:

  • RequireFullFileName: False
  • Executable: cmd.exe
  • Arguments: /c "NET USE Z: \\192.168.1.10\sqlbackup /USER:username password /p:NO"
The /p:NO at the end means that the mapping will not be persistent. This is optional.

Next step was to change the destination connections to use the new mapped drive:


Also set the DelayValidation to True for this, otherwise you will get an error because the drive has not been yet mapped.

In the end, the package would look like this:


In the last Execute process task I remove the drive with the command: /c "NET USE Z: /delete":




However, when I tried to run the package, I always got the following error message:
The specified network password is not correct.

I was not getting this error in the package execution error, but when I was trying to run the command manually.
I was running this on a Windows Server 2012, 2008 and 2008 R2 machines and there was still something left to do:
  1. Start -> run -> secpol.msc
  2. Local Policies -> Security Options -> Network Security: LAN Manager Authentication level
  3. Change to Send LM & NTLM - use NTLMv2 session security if negociated

The problem with SQL Server Agent

Although the package runs fine in BIDS I was not able to run the package from a job in SQL Server Agent. The package was not deployed to SQL Server.

The only way I was able to run it from the Agent was to create a batch file (.bat) with the command "C:\Windows\System32\net.exe USE Z: \\192.168.1.10\sqlbackup /USER:username password" and change the Execute Process Task to run the batch file:



Monday, June 16, 2014

Short tutorial for NSLayoutConstraint

When I started developing Jano I was still creating my interfaces using the initWithFrame constructor. This approach was... painful :). So I started to search for other ways to create the interface. Of course, there was the option to use XIBs, but I did not want that. This is how I found the NSLayoutConstraint class.

In this post I will use the NSLayoutConstraint class to add a label to an UIViewController on a IOS app.

Setting things up

For this demonstration I will use the Achievements view controller in my app. This is where you can see the achievements that you get in the app, the badges, the points, etc.

I prefer to create the interface elements in a separate class so I that my ViewController remains as clean as possible. Here I have the AchivementsViewController and the AchievementsViewControllerInterfaceTool.

The AchievementsViewController.h is defined as follows:



#import <UIKit/UIKit.h> 

#import "AchievementsViewControllerInterfaceTool.h"



@interface AchievementsViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> 



@property (nonatomic, strong) UILabel *lblTest;

@property (nonatomic, strong) UITableView *tableView;



@end


The AchievementsViewControllerInterfaceTool.h is defined as follows:

#import <Foundation/Foundation.h>

#import "AchievementsViewController"



@class AchievementsViewController;

@interface AchievementsViewControllerInterfaceTool : NSObject





@property (nonatomic, strong) AchievementsViewController* controller;





-(id)initWithController:(AchievementsViewController*)controller;

-(void)AddTestLabel;

-(void)AddTableView;



@end


Since both classes will reference one another (thus creating a circular dependency), in the interface tool I will add a forward declaration to the AchievementsViewController class: @class AchievementsViewController.

I will also add a table view using this class, but here I will show only how to add a UILabel to the view.

This is how AchievementsViewControllerInterfaceTool.m looks like:

#import "AchievementsViewControllerInterfaceTool.h"



@implementation AchievementsViewControllerInterfaceTool
@synthesize controller = _controller;

-(id)initWithController:(AchievementsViewController *)controller
{
       self = [super init];
       if (self) {

          _controller = controller;

       }
       return self;
}


-(void)AddTestLabel
{

_controller.lblTest = [[[UILabel alloc] init] autorelease];
_controller.lblTest.text = @"Achievements View Controller";
_controller.lblTest.translatesAutoresizingMaskIntoConstraints = NO;

[_controller.view addSubview:_controller.lblTest];
UILabel *lbl = _controller.lblTest;

NSArray * constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[lbl]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(lbl)];


[_controller.view addConstraints:constraints];

NSLayoutConstraint *c1 = [NSLayoutConstraint constraintWithItem:lbl
                             attribute:NSLayoutAttributeCenterX
                             relatedBy:NSLayoutRelationEqual
                             toItem:lbl.superview
                             attribute:NSLayoutAttributeCenterX
                             multiplier:1
                             constant:0];



[_controller.view addConstraint:c1];

}

I have created a constructor that takes as parameter a reference to the AchievementsViewController and assigns it to our internal variable, _controller.

In the first part of the AddTestLabel method I instantiate the UILabel lblTest and set the property translatesAutoresizingMaskIntoConstraints to NO. For more information about this property you can check the official documentation here.

I then define UILabel *lbl = _controller.lblTest. This is because in the next statement I have to define the visual format for the NSLayoutConstraint: "V:|-100-[lbl]". This means that I will set the label 100 spaces from the top of the superview. The superview is marked by the "|" character.

In the next constraint (c1) I set the label at the center of the superview, on the X axis only.

Friday, June 6, 2014

Posting a form to get a file in return

I was working on an ASP.NET MVC application that, at some point, had to display the PDF version of an invoice. The file was stored on 3rd party's server and the only way you could get it was by posting a form. The form had to have an action (link) set and 2 inputs, one for the password and one for the username.

In order to achieve this, there are 2 possible solutions, but (in this case) only one (Solution 2) is the right solution.

So let's begin with the first solution.

Solution 1

First we write the html for the form:

    <form id="frmInvoice" method="post" target="_blank" >

        <input type="hidden" name="user" value="@Model.UserName" id="user" />

        <input type="hidden" name="pwd" value="@Model.Password" id="pwd" />

    </form>

Not so much to say here, just that the inputs for password and username are all hidden, meaning they will not appear in the web page.

Somewhere outside the form we create a button that will submit the form through a javascript function. We could have defined the button inside the form, but in this application it was not the case.

<input type="button" value="pdf" id="@Model.InvoiceNumber" onclick="postInvoiceForm(@Model.InvoiceNumber, '@Model.ActionLink');"  />


This button will call the javascript function below:

 function postInvoiceForm(invoiceNbr, actionLink) {

        var form = document.getElementById('frmInvoice');

        form.setAttribute('action', actionLink + invoiceNbr);

        form.submit();

    }


The 'action'  is the link where the form has to be posted, something like http://www.siteWithPdfs.com/pdfid. In order for the javascript function to work I had to put the value inside single quotes.

Problem

The problem with this approach is that the username and password are visible in the page if you look at the source. This is the reason I had to go with the second option.You could use this solution if you did not have any user and password, since it would be the fastest to implement.



Solution 2

Use WebRequest instead.

In the view change the button with:

<a href="@Url.Action("GetInvoicePDF", "MyController", new { invoiceNumber = Model.InvoiceNumber })" target = "_blank">

          <img src="@Url.Content("~/Content/images/filetype_pdf.png")" alt="pdf" />

 </a>

The target = _blank is set so that I get the pdf in a new tab (or window) and I don't loose the page I was coming from.

In the MyController controller, create the method GetInvoicePDF:

public ActionResult GetInvoicePDF (string invoiceNumber)

{

   WebRequest request = WebRequest.Create("www.siteWithPdfs.com");

   request.Method = "POST";

   request.ContentType = "application/x-www-form-urlencoded";

            

   Encoding iso8859_1 = Encoding.GetEncoding("iso-8859-1");

   StreamWriter sw = new StreamWriter(request.GetRequestStream(), iso8859_1);

   sw.Write("User=");

   sw.Write(HttpUtility.UrlEncode(Model.UserName, iso8859_1));

   sw.Write("Pwd=");

   sw.Write(HttpUtility.UrlEncode(Model.Password, iso8859_1));

   sw.Close();



Stream fs = request .GetResponse().GetResponseStream();

var fsResult = new FileStreamResult(fs, "application/pdf");

return fsResult;

}


The method creates a WebRequest object that will be used to post the form. The encoding was used only because I had to prepare for nordic characters.





Wednesday, June 4, 2014

Truncating table on Linked server

I was trying to truncate a table from a linked server with a command like:
Truncate table [Linked_Server].[Database].[Schema].[TableName], but I was getting an error stating: "The object name [Linked_Server].[Database].[Schema].[TableName] contains more than the maximum number of prefixes. The maximum is 2."

The fix for his was to run the sql through sp_executesql stored procedure on the Linked server:

EXEC [Linked_Server].[Database].sys.sp_executesql N'Truncate table dbo.MyTable'

Monday, June 2, 2014

Importing data from one sqlite database to another



After some problems with Jano, a core data application for IOS, I had to take the data from an older database and put it in a new file. For this I started the Terminal application and typed sqlite, then hit Enter.

The first thing to do was to attach the 2 databases using the following command:

attach database "/Users/puiu/Documents/Jano.sqlite" as 'jano';
attach database "/Users/puiu/Documents/JanoNew.sqlite" as 'janonew';

Inserting the data was quite easy, using a simple SQL statement:

insert into janonew.zcounters(z_ent, z_opt, zisspecial, zordinal,zparent,zhiragana,zkanji,zromaji) 
select z_ent, z_opt, zisspecial, zordinal,zparent,zhiragana,zkanji,zromaji from jano.zcounters;

Tuesday, May 13, 2014

Setting page name in report

One of the advantages of using Reporting Services with SQL Server 2008 R2 or later is that you can get sheet names for Excel when exporting.
In my case I needed to export an excel file with different companies' names on the sheet name.

For this you first need to create a row group on the field you need. Then go to Row Groups, select the group like in the picture below:

Go to the properties of that group. You should see something like this:

Set the BreakLocation as you need it and the field name for the PageName.

Run your report and export it to excel. The sheet names will no longer be Sheet1, Sheet2, etc.


Wednesday, October 16, 2013

IIS error - Request entity too large


I had been working on a WCF web service lately that received the contents of a file as byte array and saved it in a database.

When calling the web-service I received the error "Request entity too large." Although the file was less than 200kb it was not able to process it.

The solution was to put the following tags inside the <system.serviceModel> tag in web.config.

<system.serviceModel>
                <bindings>
<basicHttpBinding>
<binding maxReceivedMessageSize="2097152"></binding>
</basicHttpBinding>
</bindings>
  </system.serviceModel>

Friday, September 6, 2013

Make field readonly with Javascript

In this post I will show an example of making a textbox that is bound to a model, read-only/editable when a user checks/unchecks a checkbox.

Our controls will start in the following state: the checkbox (chkIsReadOnly) is unchecked and the textbox is editable.

When the user clicks on the checkbox the following javascript function will be launched:

function changeState() {
            var checkValue = document.getElementById("chkIsReadOnly").checked;
            var userName= document.getElementById("userName");

            if (!checkValue) {
               //the field becomes readonly since the checkbox is checked
                userName.readOnly = false;
                userName.removeAttribute('readonly');
                userName.removeAttribute('disabled');
            }
            else {

                userName.readOnly = true;
                userName.setAttribute('readonly', true);
                userName.setAttribute('disabled', true);
                userName.value = '';
            }

        };

The checkbox is defined like this:
<input
                            type="checkbox"
                            name="chkIsReadOnly"
                            id="chkIsReadOnly"
                            onclick="changeState()"
  />

In order for the javascript function to work we must use the HTML helper TextBoxFor instead of EditorFor

@Html.TextBoxFor(model => model.userName, new { disabled = "disabled", @readonly = "readonly" })

Friday, August 30, 2013

Default GETDATE() contraint for column and LINQ in Entity Framework 5.0

If we have a datetime column that we want to set the default to the current date and time we can use

alter table MyTable add constraint DefGetDate DEFAULT GETDATE() FOR myColumn


In edmx, select the column from the entity and set the StoreGeneratedPatern to Computed or Identity.

The available values for StoreGeneratedPatern are:


  • None - A value indicating that it is not a server generated property. This is the default value.
  • Identity - A value is generated on insert and remains unchanged on update.
  • Computed - A value is generated on both insert and update.

The MSDN page regarding this is http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.storegeneratedpattern.aspx

Tuesday, August 27, 2013

Render file from ReportViewer connected to Reporting Services

In this post I will show how you can use a report viewer control to connect to a Reporting Services server and call the Render function on the ReportViewer.
This is useful when we don't want to show the control, but we need to get the rendered report in different formats.

Step 1: download the Report viewer runtime from here.

Step 2: Install the runtime.

Step 3: Add the reference to your project. The dll should be in \Program Files (x86)\Microsoft Visual Studio 11.0\ReportViewer\Microsoft.ReportViewer.WinForms.dll

First we create a method that will return the report from the report viewer as an array of bytes.

public byte[] RenderFromServer()
{
ReportViewer rv = new ReportViewer();

// Set the processing mode for the ReportViewer to Remote
rv.ProcessingMode = ProcessingMode.Remote;

rv.ServerReport.ReportServerUrl = new Uri("Http://mypc/ReportServer);
rv.ServerReport.DisplayName = "New report.pdf";
rv.ServerReport.ReportPath = "/Reports/MyReport";

//set credentials
ReportServerCredentials rsCredentials = rv.ServerReport.ReportServerCredentials;

NetworkCredential nc = new NetworkCredential();
nc.Domain = "myDomain"; //can also be the computer name for local access
nc.UserName = "myUser";
nc.Password = "12333";

rsCredentials.NetworkCredentials = nc;

//set parameters
List<ReportParameter> paramLst = new List<ReportParameter>();
ReportParameter rp = new ReportParameter(ParamName, ParamValue);
paramLst.Add(rp);
                        rv.ServerReport.SetParameters(paramLst);

//get the bytes from the report viewer
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;

byte[] bytes = rv.ServerReport.Render
("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);

rv.Dispose(); //very important for memory management!!
return bytes;
}


Notice that I called the Render function with the "PDF" paramater. The full list can be found at http://msdn.microsoft.com/en-us/library/ms154606.aspx.

The possible values are:

  • PDF
  • CSV
  • IMAGE
  • PDF
  • EXCEL
  • WORD
  • HTML 4.0
  • MHTML
When exporting to MHTML and you need to embed the report in another html document, or the body of an email, you have to specify the DeviceInfo details:

<DeviceInfo>
   <HTMLFragment>True</HTMLFragment>
</DeviceInfo>

As stated in MSDN, "When a report is rendered as an HTML fragment, the content of the report is contained within a TABLE element without the use of an HTML or BODY element. You can use the HTML fragment to incorporate the report into an existing HTML document."

Link: http://technet.microsoft.com/en-us/library/ms155397.aspx

Then we can write the bytes to a file:

byte[] bytes = RenderFromServer();
File.WriteAllBytes("C:\\MyReport.pdf", bytes);

Or, make a memory stream from them:

byte[] bytes = RenderFromServer();
MemoryStream ms = new MemoryStream(bytes);
ms.Seek(0, SeekOrigin.Begin);

Wednesday, July 24, 2013

Count and limit characters with Javascript

I recently had to limit the length of a text area to 250 characters so I first created the script below:

<script type="text/javascript">
            var count = 250;
            function limiter() {
                var tex = document.MyForm.MyField.value;
                var len = tex.length;
                if (len > count) {
                    tex = tex.substring(0, count);
                    document.MyForm.MyField.value = tex;
                    return false;
                }
                document.MyForm.CharsLeft.value = count - len; //display the chars left
                
            } 
</script>

After that I added the function to the onKeyUp event of the Text area. However I noticed that the count was incorrect. First of all it counted incorrectly and second, if you kept the button pressed it did not show on the page the correct number of chars left.

To fix this I also added the function to the onKeyDown event of the Text area. After that, everything was ok.


<td colspan="2">@Html.TextAreaFor(model => model.MyField, 4, 130,
                         new
                         {
                             onChange = "document.MyForm.MyField.value=this.value;",
                             onKeyDown = "limiter()",
                             TextMode = "MultiLine",
                             onKeyUp = "limiter()",
                             MaxLength = "250",
                             MaxChars = "250",
                             Rows = "2",
                             Cols = "125"
                          })
 </td>