Alternatives to using Transactional NTFS - transactional

Given that Microsoft has deprecated Transactional NTFS (TxF):
Microsoft strongly recommends developers utilize alternative means to achieve your application’s needs. Many scenarios that TxF was developed for can be achieved through simpler and more readily available techniques. Furthermore, TxF may not be available in future versions of Microsoft Windows.
While TxF is a powerful set of APIs, there has been extremely limited developer interest in this API platform since Windows Vista primarily due to its complexity and various nuances which developers need to consider as part of application development. As a result, Microsoft is considering deprecating TxF APIs in a future version of Windows to focus development and maintenance efforts on other features and APIs which have more value to a larger majority of customers.
This means that i need an alternative to:
CreateTransaction
MoveFileTransacted
CommitTransaction
My transacted requirements are fairly simple - move two files:
tx = BeginTransaction();
{
MoveFile(testResults, testResultsArchive); //throws if there's a problem
MoveFile(cdcResponse, cdcResponseArchive); //throws if there's a problem
CommitTransaction(tx);
}
finally
{
CloseHandle(tx);
}
i've thought about turning MoveFile in to CopyFile + DeleteFile:
CopyFile(testResults, testResultsArchive); //throws if there's a problem
CopyFile(cdcResponse, cdcResponseArchive); //throws if there's a problem
DeleteFile(testResults);
DeleteFile(cdcResponse);
But i was hoping for a good solution, not a buggy solution. So i try again:
CopyFile(testResults, testResultsArchive); //throws if there's a problem
CopyFile(cdcResponse, cdcResponseArchive); //throws if there's a problem
try
{
DeleteFile(testResults);
}
catch (Exception e)
{
DeleteFile(testResultsArchive);
throw e;
}
try
{
DeleteFile(cdcResponse);
}
catch (Exception e)
{
DeleteFile(cdcResponseArchive);
}
Except i was hoping for a good solution, not a buggy one.

From the link:
As a result, Microsoft is considering deprecating TxF APIs
It isn't dead yet! I don't know why they would remove an atomic file system API for Windows, even if it isn't largely supported yet. There should be a .NET BCL for ease of use leveraging TxF for starters. TxF style support for network copies would also be awesome.
If anything, Microsoft should be improving the API!

Give a try to .NET Transactional File Manager. It is fairly simple to use it safely. The following example from the page shows the way. It even looks like the author is responsive and is able to extend the library with new useful features.
// Wrap a file copy and a database insert in the same transaction
TxFileManager fileMgr = new TxFileManager();
using (TransactionScope scope1 = new TransactionScope())
{
// Copy a file
fileMgr.Copy(srcFileName, destFileName);
// Insert a database record
dbMgr.ExecuteNonQuery(insertSql);
scope1.Complete();
}
In case you are interested in your own transactional manager, be sure you check out this article. If you carefully examine the above mentioned library, you will find that it is implemented right this way.

Related

Possibility to modify or extend code in D365FO to suppress thrown error

Original class function creates an SQL query and executes it.
Since there is an syntax error in the query it throws an error. What's the correct way to achieve fixation? Class extension does not work, because CoC executes the complete original function.
originalFunction(..)
{
createSomeSQLQueryWithSyntayErrorInIt();
executeQuery();
}
The class in question is ReqDemPlanMissingForecastFiller. In method insertMissingDatesForecastEntries a direct SQL statement string is generated. The date variable nonFrozenForecastStartDate is added to the string, but is not escaped correctly as it seems.
If the SQL statement is executed, a syntax error occurs. If the statement is fixed, it can be executed e.g. in SQL Server Management Studio (SSMS).
In this specific case, based on your comments, you may be able to sidestep.
Create a new class ReqDemPlanMissingForecastFiller_Fix extending ReqDemPlanMissingForecastFiller then copy/paste the erroneous function and correct the mistake.
Create an extension class and change the newParameters static funcion.
[ExtensionOf(classStr(ReqDemPlanMissingForecastFiller))]
class ReqDemPlanMissingForecastFiller_Extention
{
public static ReqDemPlanMissingForecastFiller newParameters(
ReqDemPlanCreateForecastDataContract _dataContract,
ReqDemPlanAllocationKeyFilterTmp _allocationKeyFilter,
ReqDemPlanTaskLoggerInterface _logger = null)
{
ReqDemPlanMissingForecastFiller filler = next newParameters(_dataContract, _allocationKeyFilter, _logger);
filler = new ReqDemPlanMissingForecastFiller_Fix(); //Throw away previous value
filler.parmDataContract(_dataContract);
filler.parmAttributeManager(_dataContract.attributeManager());
filler.parmAllocationKeyFilter(_allocationKeyFilter);
filler.parmLogger(_logger);
filler.init();
return filler;
}
}
Code above was based on AX 2012 code. Stupid solution to a stupid problem.
It goes almost without saying that you should report the problem to Microsoft.
#Jan B. Kjeldsen's answer describes how the specific case can be solved without involving Microsoft.
Since overlayering is no longer possible, the solution involves copying a fair bit of standard code. This brings its own risks, because future changes by Microsoft for that code are not reflected in the copied code.
Though it cannot always be avoided, other options should be evaluated first:
As #Jan B. Kjeldsen mentioned, errors in the standard code should be reported to Microsoft (see Get support for Finance and Operations apps or Lifecycle Services (LCS)). This enables them to fix the error.
Pro: No further work needed.
Con: Microsoft may decline the fix or take a long time to implement it.
If unlike in this specific case the issue is not a downright error, but a lack of extension options, an extensibility request can be created with Microsoft. They will then add an extension option.
Pro: No further work needed.
Con: Microsoft may decline the extensibility request or take a long time to implement it.
For both errors as well as missing extension options, Microsoft also offers the Community Driven Engineering program (CDE). This enables you to develop changes in the standard code directly via a special Microsoft hosted repository where the standard code is not locked for changes.
Pro: Most flexible and fastest of all options involving Microsoft.
Con: You have to do the work yourself. Microsoft may decline the change. It can still take some time before the change is available in a GA version.
You can also consider a hybrid approach: For a quick solution, copy standard code and customize it as required. But also report an error, create an extensibility request or fix it yourself in the CDE program. When the change is available in standard code, you can then remove the copied code again.

What are the potential side effects of directly calling a stored procedure in a BizTalk helper class?

What are the potential side effects and risks of directly calling a SQL Server stored procedure in a BizTalk helper class?
I've been checking through some code and found examples like ...
private static void SaveInvoice(long id, string fileName)
{
try
{
using (SqlConnection sqlConnection = new SqlConnection("... server ..."))
{
sqlConnection.Open();
sqlCommand = new SqlCommand("usp_SaveDocument", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("#Id", id);
sqlCommand.Parameters.AddWithValue("#FileName", fileName);
sqlCommand.ExecuteNonQuery();
}
}
finally
{
sqlCommand.Dispose();
}
}
which seems like a "bad smell" in terms of BizTalk development.
But are there any real risks / limitations of doing such a direct database call in the "helper" code?
Code wise, there's really no 'risk', it's just .Net code calling SQL Server.
However, I consider it vary bad form to do so in a BizTalk app because its, well, not the BizTalk way. That would be a Schema, Map, SQL Adapter, etc.
The risk is that such an operation is essentially buried in the app, not where a BizTalk Developer would expect to find it.
My opinion:
It pretty much depends on what you are trying to achieve.
BizTalk is very good when it comes to reliable messaging and that is exactly what you are using when you are using adapters. When you are using helper classes, you need to know what you are doing, since it's a different technology. Often you are calling helper classes in orchestrations for example. You need to think differently or perhaps better about error handling, the impact of logic further down you business process, etc...
BizTalk applications can be made as generic as you can imagine and the configuration depends pretty much on the bindings (collections of send ports/receive locations, etc...) Moving from system to system can be as simple as changing a send port URI. When doing helper classes, you need a different connection string stored somewhere. This can be BTSNTSvc64.exe.config or something else. Read: something which will make your solution more complex by adding another dependency.
So, I think that calling helper classes from orchestrations is perfectly fine for certain circumstances.
This can be the case when dealing with something you need to store which is only a small data-set from the message itself. For example ensure duplicate detection/keeping own tracking.
Any case where you would need to store something from a message/instance which you would need to correlate on for example.
Saving an entire message into a SQL table by means of a helper class - for whatever reason - doesn't seem very good to me though. This deserves to be done by BizTalk adapters.
As long as you manage your connection there wont be any issue. "using" statement is recommended even for SqlCommand, we have been doing it for long time with no issues so far.

Is it OK to use WPF assemblies in a web app?

I have an ASP.NET MVC 2 app targeting .NET 4 that needs to be able to resize images on the fly and write them to the response.
I have code that does this and it works. I am using System.Drawing.dll.
However, I want to enhance my code so that not only am I resizing the image, but I am dropping it from 24bpp down to 4bit grayscale. I could not, for the life of me, find code on how to do this with System.Drawing.dll.
But I did find a bunch of WPF stuff. This is my working/sample code (runs in LinqPad).
// Load the original 24 bit image
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri(#"C:\Temp\Resized\18_appa2_015.png", UriKind.Absolute);
//bitmapImage.DecodePixelWidth = 600;
bitmapImage.EndInit();
// Create the destination image
var formatConvertedBitmap = new FormatConvertedBitmap();
formatConvertedBitmap.BeginInit();
formatConvertedBitmap.Source = bitmapImage;
formatConvertedBitmap.DestinationFormat = PixelFormats.Gray4;
formatConvertedBitmap.EndInit();
// Encode and dump the image to disk
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(formatConvertedBitmap));
using (var fileStream = File.Create(#"C:\Temp\Resized\18_appa2_015_s2.png"))
{
encoder.Save(fileStream);
}
It uses System.Xaml.dll, WindowsBase.dll, PresentationCore.dll, and PresentationFramework.dll. The namespaces used are: System.Windows.Controls, System.Windows.Media, and System.Windows.Media.Imaging.
Is there any problem using these namespaces in my web application? It doesn't seem right.
If anyone knows how to drop the bit depth without all this WPF stuff (which I barely understand, BTW) I would be thrilled to see that too.
No problem. You can easily use WPF for image manipulation from within an ASP.NET web site. I've used WPF behind the scenes within a web site several times before, and it works great.
The one issue I did run into is that many parts of WPF insist the calling threads be STA threads. If your web site uses MTA threads instead you will get an error telling you that WPF needs STA threads. To fix this, use the STAThreadPool class I posted in this answer.
My understanding (and I can't find a citation right now) is that this is officially not supported. However, in practice, it seems to work pretty well and you would not be alone in using these libraries in a Web app. Also, even if you can find a way of doing this with System.Drawing, I believe that officially that's not supported in the Web environment either -- though it is more widely used in that environment than WPF, which gives you an extra level of reassurance.

HTML to RTF Converter for .NET [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I've already seen lots of posts on the site for RTF to HTML and some other posts talking about some HTML to RTF converters, but I'm really trying to get a full breakdown of what is considered the most widely used commercial product, open source product or if people recommend going home grown. Apologies if you consider this a duplicate question, but I'm trying to create a product matrix to see what is the most viable for our application. I also think this would be helpful for others.
The converter would be used in an ASP.NET 2.0 application (we're upgrading to 3.5 shortly but still sticking with WebForms) using SQLServer 2005 (soon 2008) as the DB.
From reading a few posts, SautinSoft appears to be popular as a commercial component. Are there other commercial components that you'd recommend for converting HTML to RTF? Price does matter, but even if it's a little on the expensive side, please list it.
For open source, I read that OpenOffice.org can be run as a service so that it can convert files. However, this appears to be only Java based. I imagine, I'd need some kind of interop to use this? What .NET open source components, if any, are out there for converting HTML to RTF?
For home grown, is an XSLT the way to go with XHTML? If so, what component do you recommend for generating XHTML? Otherwise, what other home grown avenuses do you recommend.
Also, please note that I currently don't care so much about RTF to HTML. If a commercial component offers this and the price is still the same, fine, otherwise please don't mention it.
For what its worth and in no particular order.
A while ago i wanted to export to RTF and then import from RTF the RTF in question being manipulated by MS Word.
The first problem is RTF is not an open standard. It is an internal MS standard and there fore they alter it as and when they like and do not generally worry about compatibility. Currently the versions of RTF are 1.3 to 1.9 and they are all different. Internally they use twips for measurement just for good measure.
I bought the O'Reilly pocket book on the subject which helped and read a lot of the MS documentation which is good, but there is a lot of it and lots for each version.
Because of the way RTF is coded using regex to manipulate is incredibly hard work and needs careful handling and concentration to test and get to work. I use a Mac editor that had built in regex so i could steadily test each section and build it into the code.
Because of the number of versions there is also a lot of incompatibility between versions but there is a lot of commonality and in the end it was reasonably hard/easy to get where i wanted (after about a weeks reading and a weeks coding) and producing a really simple version.
I never found a commercial solution but i had to have a free on because of budget so that cut a lot out but take great care in choosing one to make sure it does what you want and has support.
I don't think where you are coming from HTML/XML/XHTML, i was converting CSV formats, it the RTF.
I am not sure if i would advise to DIY or buy. Probably on balance DIY but your own circumstances will dictate that.
Edit: One thing going from content to RTF is easier than vice versa.
BTW not criticising MS fior the RTF versions, hey it's theirs and proprietary so they can do what they like.
I would recommend doing it yourself as the task is not really that complex. Firstly, the easiest way convert one Xml format into another Xml format is with an Xslt. Converting Xml documents in C# is super easy.
Here is a good msdn blog post to get you started. Mike even mentions that it was easier to do this by hand that to deal with a third party.
link
Actually, I already answered this question here. Guess that makes this a duplicate.
I just came across this WYSIWYG rich text editor (RTE) for the web that also has an HTML to RTF converter, Cute Editor for .NET. Does anyone have any experience with this component? My main experience for web based RTEs have been CKEditor (fckEditor) and TinyMCE but as far as I can tell CKEditor and TinyMCE do not have HTML to RTF converters built in.
Since I'm required to implement some mailmerge capabilities with rich-text formatting on a Web application, I thought it'd be nice to share my experiences.
Basically, I explored two alternatives:
using Google Docs API to leverage Google Docs capabilities
using XSLT, as shown on this essay
Google Docs API works well. Problem is, when you upload an HTML document with page breaks, like this:
<p style="page-break-before:always;display:none;"/>
and ask Google to convert the doc in RTF, you lose all breaks, which does not fit my requirements. However, if page breaks aren't an issue for you, you might check this solution out.
The XSLT solution works... sort of.
It works if you reference MSXML3 COM object directly, bypassing System.Xml classes. Otherwise I couldn't make it work. Moreover, it seems to honor all but basic formatting and tags, disregarding text color, size and the like. However, it honors page breaks. :-)
Here's a quick library I wrote, using tidy.net to force HTML to XHTML conversion. Hope it helps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ADDS.Mailmerge
{
public class XHTML2RTF
{
MSXML2.FreeThreadedDOMDocument _xslDoc;
MSXML2.FreeThreadedDOMDocument _xmlDoc;
MSXML2.IXSLProcessor _xslProcessor;
MSXML2.XSLTemplate _xslTemplate;
static XHTML2RTF instance = null;
static readonly object padlock = new object();
XHTML2RTF()
{
_xslDoc = new MSXML2.FreeThreadedDOMDocument();
//XSLData.xhtml2rtf is a resource file
// containing XSL for transformation
// I got XSL from here:
// http://www.codeproject.com/KB/HTML/XHTML2RTF.aspx
_xslDoc.loadXML(XSLData.xhtml2rtf);
_xmlDoc = new MSXML2.FreeThreadedDOMDocument();
_xslTemplate = new MSXML2.XSLTemplate();
_xslTemplate.stylesheet = _xslDoc;
_xslProcessor = _xslTemplate.createProcessor();
}
public string ConvertToRTF(string xhtmlData)
{
try
{
string sXhtml = "";
TidyNet.Tidy tidy = new TidyNet.Tidy();
tidy.Options.XmlOut = true;
tidy.Options.Xhtml = true;
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xhtmlData)))
{
StringBuilder sb = new StringBuilder();
using (MemoryStream sw = new MemoryStream())
{
TidyNet.TidyMessageCollection messages = new TidyNet.TidyMessageCollection();
tidy.Parse(ms, sw, messages);
sXhtml = Encoding.UTF8.GetString(sw.ToArray());
}
}
_xmlDoc.loadXML(sXhtml);
_xslProcessor.input = _xmlDoc;
_xslProcessor.transform();
return _xslProcessor.output.ToString();
}
catch (Exception exc)
{
throw new Exception("Error in xhtml conversion. ", exc);
}
}
public static XHTML2RTF Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new XHTML2RTF();
}
return instance;
}
}
}
}
}

ASP.NET - How do you Unit Test WebControls?

Alright.
So I figure it's about time I get into unit testing, since everyone's been banging on about it for long enough. I've installed NUnit and gone through a few "intro to unit testing" type tutorials.
I'm currently putting together a small framework to help with the rebuild of one of our web apps, so I've created a VS2008 project for my framework and I want to unit test it as I go.
How on earth do I go about unit testing the WebControls? The methods are all protected or private, and since it's a framework, there isn't much else but WebControls.
Any pointers?
Burns
You can do model-view-controller or model-view-presenter type architectures without using a full blown framework. You already found out that unit-testing ui-components is difficult. There are ways around that but you probably don't want to go that route. Usually this will make your tests very hard to maintain, more maintenance nightmare's is something programmers can do without :-)
Try to separate out the functionality you want to test in a "controller" or "presenter" class. Then test that class. To make it more testable you can hide the usercontrol class (the view) behind an interface and make the controller or presenter talk to the view through the interface. That way you can mock up the view in your tests.
I know this sounds like a lot of work and it seems like a workaround but if you get used to this it's a realy nice architecture that makes it far easier to change ui behaviour. You can always start using a "real" mvc framework when you realy need it :-)
Ues the assembly:InternalsVisibleTo attribute and you'll be able to access those private members.
Put it in your webcontrol project's AssemblyInfo.cs (under Properties node)
[assembly:InternalsVisibleTo("YourTestProjectName")]
You have found the biggest pain point of ASP.NET. As far as sealed, private classes that hinder unit testing.
This is the main reason that TDD people will use a MVC framework (ASP.NET MVC, Castle MonoRail) as it provides a clear seperation from your view templates and your controller logic. The controllers are fully testable.
You could also look at testing components through the browser as a user would see them using a testing framework such as WebAii. I've seen it work and its pretty cool. I've also been told you can plug it into automated builds but I've not seen that as of yet.
Hope it helps ...
This is an old article by now, but I was using NUnitASP to write nunit tests for asp.net WebControls in 2004. That article gives a detailed example of testing a simple control using their concept of creating a corresponding "Tester" class that encapsulates the details of your control from you tests. The Tester can (should) also be in the same assembly as your control so can share some things between them (e.g. utility functions, constants, etc.).
I used the technique (and others use variants of the technique) still today to test very sophisticated controls.
I hope that is helpful.
The MVC framework mentioned above is the best way to test what the control does. However testing how it works is a bit different.
This is totally off the cuff but you could make the user control expose some protected methods and properties to return validation information and then have a testing user control inherit it. That control could populate fields, press buttons and what not. Kind of messy but it could work.
You can also take a look at this Rhino Igloo framework. It is a compromised MVC framework for WebForms.
Ivonna
can test WebControls in isolation, within the Asp.Net context
Just call session.GetControl("Path.ascx") and verify that it has all necessary properties.
You test them like this:
[Test]
public void ConditionQueryBuilderTest_RendersProperHtml()
{
var sw = new StringWriter();
var queryBuilder = new ConditionQueryBuilderStub
{
ID = "UnitTestbuilder",
QueryBuilderURL = #"\SomeAspxPage\SomeWebMethod",
ResetQueryBuilderURL = #"\SomeAspxPage\OnQueryBuilderReset",
FilterValuesCollection = new Dictionary<int, string> { {15, "Some Condition"}}
};
queryBuilder.RenderAllContents(new HtmlTextWriter(sw));
AppendLog(sw.ToString());
Assert.AreEqual(ExpectedHtml, sw.ToString()); // ExpectedHTML is the raw expected HTML
}
Here is my stub:
internal class ConditionQueryBuilderStub : ConditionQueryBuilder // ConditionQueryBuilder is a WebControl
{
internal void RenderAllContents(HtmlTextWriter writer)
{
RenderContents(writer);
}
}

Resources