Showing posts with label DotNet. Show all posts
Showing posts with label DotNet. Show all posts

Thursday, 14 May 2009

Subsonic Parent -> Child saving

How to save subsonic objects to the db that have FK values needing set.

Here's an example that also uses a transaction. Please note that you will have add a reference to the System.Transactions namespace in your project and then reference in your class.



   using (TransactionScope scope = new TransactionScope())

    {

        try

        {

            Order order = new Order();

            //populate order details.

            order.Save(); //Commit to DB





            OrderItem item = new OrderItem();

            //populate orderItem details.



            item.Order = order;   //THIS LINE SETS THE PARENT OBJECT TO ABOVE ORDER



            item.Save();  //Commit to DB



            //complete you transaction

            scope.Complete();



        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            throw ex;

        }

    }


Friday, 8 May 2009

Setting up an ASP.Net site for membership using your own database

If you are setting up a new application and you want to use the membership and roles security then normally .Net will try to set this up for you in your local express server. If however you want to set this up in your application database, on your main server then do the following.

1) Run C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe
2) Use the wizard to select the server and database. (I believe this can be any of 2000/05/08)
3) Change the following in your web config to suit your DB and server settings. Cahnge any other settings to suit your application. Click here for MSDN article.


<configuration>

<connectionStrings>

<add name="MySqlConnection" connectionString="Data

Source=YOURSQLSERVENAME;Initial Catalog=YOURDBNAME;Integrated

Security=SSPI;" />

</connectionStrings>

<system.web>

<authentication mode="Forms" >

<forms loginUrl="login.aspx"

name=".ASPXFORMSAUTH" />

</authentication>

<authorization>

<deny users="?" />

</authorization>

<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">

<providers>

<clear />

<add

name="SqlProvider"

type="System.Web.Security.SqlMembershipProvider"

connectionStringName="MySqlConnection"

applicationName="MyApplication"

enablePasswordRetrieval="false"

enablePasswordReset="true"

requiresQuestionAndAnswer="true"

requiresUniqueEmail="true"

passwordFormat="Hashed" />

</providers>

</membership>

</system.web>

</configuration>






4) That should be you!


I got this info by using StackOverflow and asking this question.



Friday, 10 October 2008

Put your application in the system tray

Found this blog. East step by step guide on how to setup your application to run in the System Tray.

http://www.developer.com/net/csharp/article.php/3336751

Enjoy!

Thursday, 9 October 2008

Run a DTS package through an application

To run a dts package through code:

Using:
using System.Threading;
using DTS;

Declare:
private Thread dts;

Method:
private void CallDTS()
{
dts = new Thread(new ThreadStart(RunDTSPackage));
dts.Start
}

private void RunDTSPackage()
{
try
{
object obj = new object();

PackageClass csDTS = new PackageClass();
csDTS.LoadFromSQLServer("Server", null, null, DTSSQLServerStorageFlags.DTSSQLStgFlag_UseTrustedConnection, null, null, null, "PackageName", ref obj);
csDTS.Execute();
csDTS.UnInitialize();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

You might need to wait until the package is finished running before you carry on and call other methods so check for:
while (dts.IsAlive)
{
}
DoSomething();

Thats it.

Check if an instance of another app is open

The following method checks to see if an instance of a specific application is running.....

using System.Diagnostics;

private bool CheckIfPPlusOpen()
{
Process[] pApps = Process.GetProcesses();
bool bPPlus = false;
foreach (Process p in pApps)
{
if (p.ProcessName.Equals("P+Test"))
{
bPPlus = true;
}
}
if (!bPPlus)
{
GetPPlusAbsenceData();
}
else
{
MessageBox.Show("Please close P+ before refreshing the P+ data!", "Close P+", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
return bPPlus;
}

Stop multiple instances of your windows app running

I needed to stop users from starting up more than one copy of the MyTime app running and I found this link to help.

I changed where the code actually runs, I think its a bit better this way.

1. Open up the Program.cs file.

2. Add System.Threading into the using list.

3. Paste this in the class declaration
private static Mutex mutex;
private static string mutexName = "MyTime.Mutex";

4. Paste this in the main() method before any other code runs.
try
{
mutex = Mutex.OpenExisting(mutexName);

//since it hasn’t thrown an exception, then we already have one copy of the app open.
MessageBox.Show("A copy of MyTime is already open.",
"MyTime", MessageBoxButtons.OK, MessageBoxIcon.Information);

//use this command as we haven't called the run method of the application
Environment.Exit(0);
}
catch
{
//since we didn’t find a mutex with that name, create one
mutex = new Mutex(true, mutexName);
}

//Hook up the Application Exit event to release the mutex so that the app can re-open correctly.
Application.ApplicationExit += new EventHandler(delegate { mutex.ReleaseMutex(); });


5. Thats it. Test it!


Don't think there is much else to this. Any questions let me know.

Thursday, 18 September 2008

Infragistics problem when deploying asp.NET app

Document title:
Infragistics problem when deploying asp.NET app
What is it?

When deploying an Asp.NET app to the server you need to make a few changes to the web.config file and make sure you have the correct dll files in order for it to run correctly.

For every Infragistics control that you use in the application, move over the corresponding dll file from c:\Program Files\Infragistics\NetAdvantage 2004 Volume 3\ASP.NET\bin on local machine into bin folder in application folder on server.

You also need to change the web.config file if the Infragistics version on the server is different than the one you are developing with.

To find out which version the server is running:
· Go to webapps folder on server then Infragistics\20043\Scripts.
· Open any of the .js files in this folder and the comments at the top tell you which version.
· Currently all servers have version 4.3.20043.27.

To add new version for your app:
· Inside applications folder on web server add a folder called Scripts.
· Copy all .js files from C:\Inetpub\wwwroot\aspnet_client\infragistics\20043\Scripts on local computer into the new scripts folder.

Sometimes need to add new location for infragistics images, appears to be no rhyme or reason for this but if all images are appearing blank on server then it’s needed.

To add the new infragistics images location for app:
· Inside applications folder on web server add a folder called InfragisticsImages.
· Copy contents of C:\Inetpub\wwwroot\aspnet_client\infragistics\Images on local computer into the new InfragisticsImages folder.

Finally in the web.config add:
· At the top of the web.config file add a tag. Could already be there as this is the same tag that ExceptionManagement section is entered into.
· Inside the tag add:
this tells the XML to register a new tag called
· Underneath the close of the tag add: this tells the XML where to find new scripts and image directories.

Sample web.config file with this added on following pages.





































































Report Viewer in .Net App

Weekly Interest Topic
Report Viewer in .Net App
Date Created/Revised
July 2006
Owner: Martin Dearie
Why did you look into this?

I am currently developing an application that requires a report to be run within the main process flow of the application.
Using a link to a report in Report Manager would take the user outside of the control of the application, this is not acceptable in this application and another solution must be found.

Since we have moved to Crystal I had to find a way to integrate this type of report into my application.

What did you find out?

Once in Visual Studio from the Toolbox, open the Crystal Reports node to locate the CrystalReportViewer control.

Drag the CrystalReportViewer control onto the Web Form. The “CrystalReportViewer Tasks” Smart Task panel opens.

On the upper-right corner of the CrystalReportViewer control, click the small triangular button.

Click the Choose Report Source list and select .

The Create ReportSource dialog box opens.

Click the Specify a report for the CrystalReportSource control list and select

Click Ok

Where did you find this out?

This information was taken from the Crystal Reports For Visual Studio 2005 .pdf

Other information

Report Viewer in .Net App

Weekly Interest Topic
Report Viewer in .Net App
Date Created/Revised
Feb 2006
Owner: Joanne Conway
Why did you look into this?

I am currently developing an application that requires a report to be run within the main process flow of the application.
Using a link to a report in Report Manager would take the user outside of the control of the application, this is not acceptable in this application and another solution must be found.

Since we have moved to MS Reporting Services I had to find a way to integrate this type of report into my application.

What did you find out?

Microsoft have deployed a sample Report Viewer control in the samples directory of reporting service. This is a Server Control which uses URL access to render reports within a web browser.

The control is installed under C:\Program Files\Microsoft SQL Server\MSSQL\Reporting Services\Samples\Applications\ReportViewer \cs.

A Dll is created once the above application is has been deployed which can then be used within any application.

Where did you find this out?

There are lots of documents available on the internet and I have attached the file I used to this document.

Other information
Useful code:

Set the Server URL :
ReportViewer1.ServerUrl = "http://dcSQL2/reportserver";

Set the Report Path :
ReportViewer1.ReportPath =
"/ICT/Application Reports/Purchase Order Register/Purchase Order" ;

Pass in parameter:
ReportViewer1.SetQueryParameter("IN_PurchaseOrderId",Session["PurchaseOrderid"].ToString());

Rendering format can be set within the report viewer properties

Creating Reports with SQL Reporting Service and Visual Studio .NETBy Akram Hussein
Introduction
The following article will give you a quick start on how to use the new reporting service of Microsoft inside your ASP.NET Application. It is relatively very easy to use reporting services, however it is a bit different from what we are used to in Crystal reports.
Background
Reporting service is basically a reporting server that uses SQL server as its backend database, all reports are deployed on the reporting server and from their you can access any reports you have access rights to. The basic idea is to have a single location where all reports are deployed, and provides a single point of access, this created a very flexible environment to deploy your reports over the enterprise. The idea is a very similar to Crystal Reports Enterprise Reporting.
Requirements:
You will need the following tools before installing the reporting service, those tools are needed for development of reports for deployment you will need exactly the same environment without Visual Studio .NET
SQL Server 2000 with SP3
IIS 5.0 or 6.0
Visual Studio .NET
Accessing Report Server Management Interface:
You can start by accessing your reporting service by going to http://localhost/reports this is where you can manage your reporting service. You can view reports and other information directly from this web interface, manage subscriptions, security, data sources and other. Mostly we won’t be using it in this article except for viewing reports.














The Reporting Service Web Management provides browsing folders that contain reports, data source names that you have deployed. This tool provides viewing of reports, however for developing reports you must have Visual Studio .NET














The above figure shows the report server windows service, as you can see it must be running to be able to access, view and deploy reports from your development tool
As I write this article I heard from Microsoft that they have bought a tool that can provide creating reports directly from the reporting service web interface, I do not have any information when it will be released but hopefully soon.
Developing Your Own Reports
1. Creating Your First Report
First you create a new project, and select Report Project this will create a reporting service project. From here you will find two folders shared data sources, and reports. Shared data sources is one very interesting feature, this is where your data source for your reports. You can have more than 1 shared data source or even a single data source for every report, however it wouldn’t be a good idea to repeat the same data source twice if you are using the same database.














2. Creating a Shared Data Source
Here just create a shared data source selecting your SQL server, Northwind database, we will be using basically the Northwind database to build a very simple report to list all our customers.
3. Selecting Data
Before selecting the data for your report, just click on new report and choose the wizard, it will take you step by step. First select the data source that you have just created, then select the table, choose any table you like, in this example I chose the customer table. Then select tabular, and then select all data fields into the detail list box. After you are done, go to the Data Tab of your report you will find table customer, with all fields select here you can alter the table or fields you want to select in your report, just as you are used to when creating a view in SQL Server.




















4. Selecting Design
After you are done selecting the data go to, report designer select the layout tab in your report, as you can see in the left toolbox you can use any of the report control to enhance your report functionality and design. You can include charts, images, matrix, etc.. after you’re done lets preview the report.



















5. Previewing Report
One of the features I love about the reporting service, is the ability to preview your report before deployment, here you can view your report as if you are in the deployment environment.














6. Deploying Report on Report Service
The deployment part is tricky now, you do not just include a reporting customer control in your ASP.NET page and that’s it, well you have to first deploy them on your reporting service Server. Ok now as we said all your reports are developed on Visual Studio .NET then they are deploying to a reporting server, either on your machine, intranet, or internet anywhere you want them as long you have access rights to that reporting server. To start deployment right click your application and select properties, the following window will appear. You will find the property “OverwriteDataSources” to be false, make it to true, then select the target folder, this can be anything you like. Then enter the location of your reporting server here it is localhost however it can be a domain, IP address or any location you want as long as reporting service is installed to it. After you are done press F5 or right click the project and select deploy, the minute this is done your reports are deployed on your reporting server.














7. Viewing Report from Report Service
As I said now your report is deployed on the reporting server you can access it directly by going to http://localhost/reports , select the folder you installed the report in then select your report. The report should appear like the one shown below:





















8. Including ReportViewer Custom Control in your ASP.NET Application
Now the tricky part on how to include this report in your ASP.NET application, here you will need to use a custom control however, Microsoft does not provide a custom control like crystal report viewer custom control, in fact you will find it deployed in the samples directory of Reporting service. The custom control is located at
C:\Program Files\Microsoft SQL Server\MSSQL\Reporting Services\Samples\Applications\ReportViewer
You can just go and open that project and compile it and use the ReportViewer DLL in your ASP.NET application. This can be done by opening your toolbox, then click Add/remove and click browse and select the ReportViewer.DLL I included the source and the DLL in the source in case you cannot find it or you didn’t install the sample applications of reporting service. Anyway after selecting the DLL you have to select the custom control from the list as shown below:
You will find the name of the Custom Control ReportViewer “Microsoft Sample Report Viewer Application”
When you are done, just include the custom control in your ASP.NET page and change the following properties.


First you have to select the report path and this should be something like :- My Reports/Report1 - exactly the sample folder you deployed your reports in.
Second you have to edit the ServerURL and here you enter your reporting service location http://localhost/reportserver/ this is the reporting server location, while /reports is the report server web management so take care not to get mixed up.
Once both are done, you can start viewing your report by accessing your ASP.NET web page.



























9. Viewing your ASP.NET Application, including your Report
Now enter the location of your web application and choose the asp.net page that contains the custom control, and bingo here you find your report as shown below. See how easy











Conclusion
Now you can create as much reports as you want and use the custom control to view them by just changing their reportpath this can be done at runtime.




































Wednesday, 17 September 2008

Visual Studio 2008 Interesting features

Visual Studio 2008


JavaScript Features

JavaScript support in Visual Studio 2008 has been greatly increase and now has intellisense similar to C# coding. It also allows us to debug our JavaScript by the user of breakpoints and stepping through code. This will be a huge benefit to the team as we can leverage our existing debugging skill set at the web presentation layer of our applications.

LINQ (VS 2008)
LINQ in Visual Studio 2008 provides standard development syntax for accessing data, regardless of where the data resides. For example, the same syntax can access either SQL Server or XML data. LINQ is used rather than TSQL inside the application language, such as C# or VB.
Entity Data Services
ADO.NET Data services in the 3.5 version of the .Net framework now allows for high level business objects to be created, such as Customers or Parts. These entities can be used rather than the standard method of returning individual rows and tables. If you’re using E-R (entity relationship) modelling, your objects in SQL will now match your modelling. There are several new ADO.NET frameworks that can access these entities such as the Line-of-Business (LOB) framework and the Entity Query Language (eSQL).
Image Library

Visual Studio now contains standardised images from Windows, Office and other Microsoft software to keep your software consistent with Microsoft. This will give our application a familiar look other Microsoft products and look very professional in a commercial environment.


Plug-ins

Visual Studio 2008 extends the ability to create plug in tools for the IDE. Plug-ins are not something that we as a department will develop, however there are a greater number of plug-ins to increase our productivity available on the web. For instance the Class Builder wizard plug-in reduced the amount of code for new classes. There are a number of these that are available for free.

Unit testing

Visual Studio 2008 ships with a built in unit testing that allow use to build on our existing testing skills. Currently we use an added tool, NUnit, to perform automated testing. With 2008 we will have another tool at our disposal to increase the options we have when it comes to the testing of our applications.

Visual SourceSafe

We currently use the 2005 version of this software. Visual Studio 2008 requires an update to be compatible with VS2008. This currently available for download from the Microsoft web site and will not require a license upgrade for Visual SourceSafe
Link:
http://www.microsoft.com/downloads/details.aspx?FamilyID=8a1a68d8-db11-417c-91ad-02aab484776b&displaylang=en

Improved HTML and CSS features

The latest version of Visual Studio provides a split view when developing the HTML presentation layer page. We can now view the HTML alongside the design view, removing the time spent swapping between views to see how our changes have affected the look of the page.

There is also a CSS Style manger that increases the support for CSS in Visual Studio and also provides intellisense. There are also a few very useful tools to help the developer use CSS. This is a relatively new area for the team and these new supporting tools will be great help in an area where we are currently lacking.


Code editing enhancements

Visual Studio 2008 provides many enhancements to the code edit in C# files. It provide the developer with a hot key(CTRL) to make the intelisense transparent to avoid hiding the code we are currently working, this was a really frustrating problem in the older versions.

There is also improved refactoring tools and one of the interesting ones checks what “Using” statements are need in a class file removing any unnecessary ones. This will reduce the file size if we have links to code libraries we don’t require.


Migration Options
Visual Studio 2008 provides Multi-Targeting Support. This means that a developer can develop applications in versions 2.0, 3.0 and 3.5. This allows us to deploy applications to machines without the latest framework installs.

As with previous version of Visual Studio, 2008 provides us with a Project upgrade tool to import older projects.

As Visual Studio is only development tool and not installed on a server there are no issues in regards to older applications. It will simply allow us to take advantage of the latest tools in the IDE to improve our productivity and ultimately the quality and security of our final products.

Monday, 4 August 2008

Windows installer - Remove Previous Versions

http://www.simple-talk.com/dotnet/visual-studio/updates-to-setup-projects/

Excellent link and explains how to unisintall previous versions of your application.

Note that the version number in the article refers to the installer version number that is accessed in the properties window. This must also being at 1.0.0 or above, otherwise the RemovePreviousVersions property won't pick it up as a previous version and won't work.

Enjoy!

Wednesday, 9 July 2008

Setting all Columns Read Only value

There are occasion where we may want to set all read only properties of our data columns to false or true. When we instantiate our dataset using our Dal.GetSchema() method it can set certain fields to ReadOnly, when we actually want to write to them at the front end. Here's a function to change this.

///
/// Set all columns property readonly to false
///

private void SetReadOnlyFalse(DataSet ds)
{
foreach (DataTable dt in ds.Tables)
{
foreach (DataColumn dc in dt.Columns)
dc.ReadOnly = false;
}
}


Note that we can easily change the code to make the entire Dataset readonly.

///
/// Set all columns property readonly to true
///

private void SetReadOnlyTrue(DataSet ds)
{
foreach (DataTable dt in ds.Tables)
{
foreach (DataColumn dc in dt.Columns)
dc.ReadOnly = true;
}
}

Or we could pass a parameter to our function to allow us to use one fucntion for both operations.

///
/// Set all columns property readonly to the boolean blReadOnly
///

private void SetReadOnly(DataSet ds, bool blReadOnly)
{
foreach (DataTable dt in ds.Tables)
{
foreach (DataColumn dc in dt.Columns)
dc.ReadOnly = blReadOnly;
}
}


Please note that the code for the Dal.GetSchema just returns an empty dataset structure for a set of table from our SQL server database. The code discussed here will work for any dataset in .Net

Wednesday, 11 June 2008

Getting the current User Name in Windows programming

Use this for getting the user name when building a windows application in DotNet. Done!
--------------------------------------------------

//
Place this at the top, above your namespace declaration
using System.Security.Principal;


//In a specific event, place the following.
string a;
a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

Monday, 9 June 2008

Using TryParse() in C#

When we are validating integer input, usually from a textbox, we need to make sure that the text is a valid integer before we set the properties in our class.

We would normally have done this using the following type of code:

try
{
SomeInt = Convert.ToInt32(tbSomeInt.Text);
}
catch (Exception ex)
{
MessageBox.Show("Some int must be a valid integer");
return;
}

By using a try catch in this manner we add quite a bit of overhead to the work that the .Net framework has to do for us. We can use the TryParse() method to get round this.

int intSomeInt;
if (int.TryParse(tbSomeInt.Text, out intSomeInt) == true)
{
//if the conversion succeded
csSomeClass._SomeInt= intSomeInt;
}
else
{
MessageBox.Show("Some int must be a valid integer");
return;
}

This avoids the overhead of using the try and will run faster. Please note that you cannot use a class property in the out parameter of the method and must use a variable as above.

Here is a link to another blog that I found useful.
Free Hit Counter