Wednesday, December 28, 2011

ActiveX controls at asp.net


As web application developers, we want to give our users a highly functional application. We want to provide our users with functionality like printing ,scanning images etc., but it is difficult due to the security and the disconnected architecture of the Internet .

1. create an activeX control
   a. create interface
     public interface ITest
    {
        string Name { get; }
        string SayHello(string str);
    }
    b.create class
     [Guid("a991dd50-ff67-47b0-a4c3-f2b3e9fbd0f4")]
    [ComVisible(true)]
    [ProgId("Test.Test")]
    public class TestClass:ITest
    {
         public string Name
        {
            get  { return "My Test Name"; }
        }
        public string SayHello(string str)
        {
            return "Hello " + str;
        }

    }
   c.register the activeX control:
      at the project properties window => build => check => "Register for COM interop"
2.Host control at wweb application
    a. add object tag to the html page
      <object classid="CLSID:a991dd50-ff67-47b0-a4c3-f2b3e9fbd0f4" id="myCtrl" />
    b. access the object and the functions/properties from javascript
      var myAx = new ActiveXObject("Test.Test");    => the name of ProgId
            alert(myAx.Name);  

   an example for the html:
     <script type="text/javascript">
        function getProperty() {
            var myAx = new ActiveXObject("Test.Test");
            alert(myAx.Name);
        }
        function getName() {
            var myAx = new ActiveXObject("Test.Test");
            var text = document.getElementById("myName").value;
            alert(myAx.GetMe(text));
        }
    </script>
    <table>
        <tr>
            <td>
                <input type="text" id="myName" />
            </td>
            <td>
                <input type="button" value="Property" onclick="getProperty()" />
            </td>
            <td>
                <input type="button" value="Function" onclick="getName()" />
            </td>
        </tr>
    </table>
    <object classid="CLSID:a991dd50-ff67-47b0-a4c3-f2b3e9fbd0f4" id="myCtrl" />

       

Sunday, December 25, 2011

Microsoft Reportviewer deployment


Dlls required for Microsoft reportviewer deployment
1 .Microsoft.ReportViewer.WebForms.dll or Microsoft.ReportViewer.WinForms.dll
2. Microsoft.ReportViewer.Common.dll


Aslo setup the Reporting Redistributeable version that corresponding to the version that used at the development , for example if you use reportViewer version 10 then you have to set up the  

Thursday, December 22, 2011

RDLC reports at MVC project


RDLC reports cannot have connection string and can't directly connected to the database , instead we use the "Object" datasource to provide data to the reports.

The "Object" datasource provides, at the design time , the report by the structure of the data that  will be passed to the report at the runtime

The datasources cannot be added to the MVC project so we need a class library that the datasources will be built upon

Steps

  1. create a class library project 
  2. add the "ViewModel" class -- that will have the structure of the data 
  3. for example
public class PatientViewModel
{
public int Id{get;set;}
public string Name{get;set;}
}
    4. at the solution explorer , select the ViewModelClassLibrary project
    5. at the menu bar => Data => select =>Add New DataSource 
    6. Data Source configuration wizard open => select "Object" Data source =>Next
    7.  select "PatientViewModel " class => finish
    8.create the MVC project 
   9. add new folder called "forms" at the project main folder
  10. add new rdlc report to the folder 
  11 . open the report => at the view menu => press " report data"
12 .create new datasets  => in the list , you will find the created data source at point  (7)
 and give the dataset a specific name => for example => PatientDataSet
13 . at the controller  , create an action for the report
 public ActionResult GetReport()
        {
            LocalReport rep = new LocalReport();
            rep.ReportPath = Server.MapPath("~/Forms/MyReport.rdlc");
            List<PatientViewModel> patients = GetPatients();
            rep.DataSources.Add(new ReportDataSource("PatientDataSet", patients));
 
            //Render the report
            _renderedBytes = rep.Render(
                _reportType,
                _deviceInfo,
                out _mimeType,
                out _encoding,
                out _fileNameExtension,
                out _streams,
                out _warnings);
 
            return File(_renderedBytes, _mimeType);
 
        }





Multiple validation summary at single page

The problem:
at razor , if we have 3 partial views each contains a validation summary control
when the validation works, and the validation summary supposed to give the usual red text , all the validations summary controls will view the error , even if the element that have the problem is not it its own view
example 

The solution:
the solution is to draw the validation summary only when you validate your form for example
  1. at the controller of "RegisterForm" , set the  Session["ValidationSummary"] = "RegisterForm"
  2. at the controller of "LoginForm" , set the  Session["ValidationSummary"] =  "LoginForm"
  3. at the   RegisterForm view
                    if ( Session["ValidationSummary"] == "RegisterForm")
            { 
   @Html.ValidationSummary(); 
            } 

    4. at the    LoginForm  view 
       if ( Session["ValidationSummary"] == " LoginForm ")
            { 
                   @Html.ValidationSummary(); 
            } 

       



you can find nother solution here NamedValidationSummary 



Error with MVC telerik


when using Telerik components , it may give you the erorr:
 "Unable to set value of the property '__MVC_FormValidation': object is null or undefined"
 solution :
 let the style sheets registeration to be:
 @(Html.Telerik().StyleSheetRegistrar() .DefaultGroup(group => group
                                                                                   .Add("telerik.common.css")
                                                                                    .Add("telerik.Vista.css")
                                                                                   .Add("telerik.rtl.css") ) )

 instead of :
 @(Html.Telerik().StyleSheetRegistrar() .DefaultGroup(group => group
                                                                                   .Add("telerik.common.css")
                                                                                    .Add("telerik.Vista.css")
                                                                                   .Add("telerik.rtl.css")
                                                                                  .Combined(true)
                                                                                   .Compress(true) ) )

Monday, November 28, 2011

Wix Sql:SqlString element - the SQL string format

For the SQL string to get correctly resolved some format rules must be followed:
1- Any Wix properties must be inside square brackets [].
2- Any square brackets that belong to SQl indeces that must be escaped: "[" -> "[\[]" AND "]" ->"[\]]".
3- Each Sql command mus tbe terminated by a semicolon ";".
4- If you use "Execute (N' bla bla ' );" then any string INSIDE this command must have an additional starting and trailing single quote.

5- If you use "Execute (N' bla bla ');" then any double quotation must be escaped by using 'ampersandquot;' instead of ' " '.
The following snippet illustrates each of the previous rules

<Sql:SqlString Id="FillAdjustmentDefinitionsTable" ExecuteOnInstall="yes" ExecuteOnReinstall="yes" Sequence="3" SqlDb="MasterDB" ContinueOnError="no"
SQL="USE DentalDB ;
SET ANSI_PADDING ON ;
Execute(N'CREATE TABLE #tempAdjustmentDefinitionTable(ThisLine xml);
bulk insert #tempAdjustmentDefinitionTable from ' '[APPLICATION]InitialDB\AdjustmentDefinitions.xml' '
with ( codepage=' 'ACP ' ')
INSERT INTO &qout;AdjustmentDefinition"
(
Type,Description,Amount
)
Select
ThisLine.value(' '(AdjustmentDefinition/@Type) [\[]1[\]] ' ', ' 'int' ') ,
ThisLine.value(' '(AdjustmentDefinition/@Description) [\[]1[\]]' ', ' 'nvarchar(100)' '),
ThisLine.value(' '(AdjustmentDefinition/@Amount) [\[]1[\]] ' ', ' 'money' ')
from #tempAdjustmentDefinitionTable
DROP TABLE #tempAdjustmentDefinitionTable ; ' ); "></Sql:SqlString>

Wednesday, November 23, 2011

custom events at .net framework

The following procedure demonstrates how to add events that follow the standard .NET Framework pattern to your classes and structs.

//1. Define a class to hold custom event arguments
public class CustomEventArgs : EventArgs
{ // add the properties and attributes that needed to be passed in the event arguments
public CustomEventArgs(string s)
{
message = s;
}
private string message;

public string Message
{
get { return message; }
set { message = value; }
}
}

// 2. Class that publishes an event
class Publisher
{
// Declare the event using EventHandler
public event EventHandler MyCustomEvent;
}

//3. Class that subscribes to an event
class Subscriber
{
public Subscriber()
{
Publisher pub=new Publisher();
// Subscribe to the event using C# 2.0 syntax
pub.MyCustomEvent += new EventHandler(MyCustomEvent_Handler);
}

// Define what actions to take when the event is raised.
void MyCustomEvent_Handler(object sender, CustomEventArgs e)
{
// the event handler
--------> third line at execution
}
}

//4. class to raise the event

class Raiser
{
public void Mani()
{
Publisher pub=new Publisher(); -------> first line at execution
pub.MyCustomEvent(new CustomEventArgs("testing")); -----> second line at execution
}
}

Friday, November 18, 2011

ASP.NET Report Viewer 2010 Auto Resize

The ASP.NET Report Viewer provides a wonderful job when viewing local or server (remote) reports beside its rich feature provided like printing, exporting and report and pages navigation tools

But the report viewer control itself didn't provide any tools to display the report control inside web controls correctly to stretch in height.

To solve the problem, JavaScript methods can resize the report viewer control to fit inside its control height as follows:

  1. When document is ready do the following
    1. Start a timer to enforce the report viewer height change. This timer is important because the report viewer height is not adjusted until it is fully loaded. If we change the height before the report viewer finished loading the report, the original report viewer height will be used
    2. In the timer function, we adjust the report viewer height
    3. Clear the timer when the report viewer height adjusted successfully
  2. When document window resize, set the report viewer height again
  3. Report height calculation is calculated to fit the window height minus the report viewer control toolbar to avoid displaying vertical scroll bar in the report viewer container

Note that you should set the SizeToReportContent property to false to avoid the report viewer auto calculate its height to fit the report content height.

The below ASPX page code describes how to fit the report viewer to the entire window of the browser (tried in IE 9 and chrome)

<%@
Page
Language="C#" AutoEventWireup="true" CodeBehind="ReportViewer.aspx.cs" Inherits="NCS.Website.Reports.ReportViewer"
%>


 

<%@
Register
Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"


Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb"
%>

<!DOCTYPE
html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


 

<script
type="text/jscript" src="../Scripts/jquery-1.5.1.min.js">

</script>

<script
type="text/jscript">


 


var reportViewer = $('#<%= this.ReportViewer1.ID %>_ctl10').parent('td');


 


var rvId = '<%= this.ReportViewer1.ID %>';


 

$(document).ready(function () {


 


// Enforce height on the report viewer


 


var oldHeight = reportViewer.height();


 


// Poll the report height so it can be set after the Report Viewer has


 


// fully loaded. Otherwise the RV will default to original config


 


var intevalId = setInterval(function () {


 


if (reportViewer.height() != oldHeight) {


 

clearInterval(intevalId);


 

}


 


var rv = $find(rvId);


 


if (!rv.get_isLoading()) {


 

SetHeight(reportViewer, rvId);


 

}


 

}, 1000);


 


 


 


// Resize report viewer when windows resizes


 

$(window).resize(function () {


 

SetHeight(reportViewer, rvId);


 

});

});


function ReportHeight() {


var windowHeight = $(window).height();


var reportBar = $('span#ReportViewer_Toolbar').height();


var totalReportHeight = windowHeight - reportBar;


return totalReportHeight;

};


function SetHeight(rptViewer, rvId) {


 


var rv = $find(rvId);


 


if (!rv.get_isLoading()) {


 

rptViewer.css("height", ReportHeight() + "px");


 

}


 

};

</script>


 

<html
xmlns="http://www.w3.org/1999/xhtml">

<head
runat="server">


<title></title>

</head>

<body>


<form
id="form1" runat="server">


<asp:ScriptManager
runat="server"
/>


<div>


<rsweb:ReportViewer
ID="ReportViewer1" runat="server" Width="100%" Height="100%"


ZoomMode="FullPage" ShowDocumentMapButton="False" AsyncRendering="True" SizeToReportContent="False">


</rsweb:ReportViewer>


</div>


</form>

</body>

</html>


 

Waiting your comments…

Thursday, November 17, 2011

Dart, Google's Programming Language for the Web

Google's alternative to JavaScript is not called Dash; the name has been changed to Dart. Designed as an object-oriented programming language that's both flexible and structured, Dart should be familiar to Java and C++ programmers, while inheriting some advantages of scripting languages like JavaScript.
Dart is a new class-based programming language for creating structured web applications. Developed with the goals of simplicity, efficiency, and scalability, the Dart language combines powerful new language features with familiar language constructs into a clear, readable syntax.

Dart is flexible because it's both static and dynamic, it's both for clients and servers and it's useful for both small scripts and large projects. Dart apps are easier to debug, to maintain and to develop collaboratively. The language is optimized for performance and doesn't allow programmers to use features like defining constants that have to be computed at runtime.
For now, no browser supports Dart, but it's likely that Chrome will address this problem in the near future. The code can be executed "either on a native virtual machine or on top of a JavaScript engine by using a compiler that translates Dart code to JavaScript." Google already provides a simple online IDE called Dartboard that lets you edit a small program using your browser, but Dartboard will evolve into a full-fledged online IDE.
It will be difficult to convince developers and browser vendors to adopt the new language, but the fact that it's easy to convert Dart code to JavaScript is an important advantage. Google will promote it "as the language for serious web development on the web platform" and will "actively push for its standardization and adoption across the board". After all, "the goal of the Dart effort is ultimately to replace JavaScript as the lingua franca of web development on the open web platform." It's hard to say whether it will succeed, but it's worth trying to fix JavaScript's flaws by starting from the scratch. Google will have standardize the language, build development tools and develop powerful apps that use Dart to make a better case.

Wednesday, November 16, 2011

MVC validation by Data Annotation ---Razor view --- Entity Framework 4.1

1- create parial class with the same namespace of the original class that is generated with the Entity framework :
namespace myNamespace
{
[MetadataTypeAttribute(typeof(Metadata))]
public partial class MyClass
{
private class Metadata
{
[Required]
public object Property_1{ get; set; }
}
}
}
2-enable client validation in the view:
@{ Html.EnableClientValidation(); }
@using (Html.BeginForm())
{

}
3- add the validation controls :
@Html.ValidationMessage("Property_1","*") // where "Property_1" is the property name which need to be validated

4- modify the controller to handle the validation : for example in the action we provide 2 different pathes , one for isValid== true another for is valid == false:
for example:
if (ModelState.IsValid)
{
// do work
}
else
{
// another work
}

Wednesday, November 9, 2011

SQL 2005 Replication Hell

Here in Nebras we are using SQL 2005 Replication to deploy solution for synchronizing our clients multi-branches sites to avoid centeral data store which doesnot work with the unreliable internet connections available here in Egypt.

Also this kind of replication is two way replication with instant synch, in other words what happen in branch 1 should appear in branch 2 instantly if connection is up.

So our choice was SQL 2005 Transactional Replication with Updatable Subscribers.

The main pain was in solving replication issues which concentrate in:
1- If connection is not reliable, the replication start conflicting without any way to find the reason of conflict. Is it data conflict due to concurrency or a conflict due to a failed stored procedure?
2- Triggers are a real hell in SQL 2005 Replication. You need to full understand the replication operations internals to be able to solve the triggers/replication issues
3- The replication logs didn't deliver that much information to be able to find the core  cause of replication conflicti ssue
4- The SQL Replication Monitor is a joke. you cannot rely on it to really monior or find problems in your replication deployment. And the Monitor itself causes issues to the replication monitor parameters if left open for long period of time.
5- The SQL BOL is really not helpful to understand the internals of SQL Replication which is necessary with business requirement challenges here in egypt

In the next post I will provide some usefull links that may help you in your transactional replication problems regarding main causes of data conflict which is not based on data concurrency.

Also in future posts I will introduce SQL 2008 Replication deployment experience and I will give a comparison with SQL 2005 Replication (the odds and evens)