.NET Diary

November 20, 2009

Error: The type ‘YourType, YourAssembly’, provided as the Service attribute value in the ServiceHost directive could not be found – Problem while using WCF

Filed under: ASP.NET, All — leoullas @ 4:13 am

Error lied in ServiceIHaveMade.svc file. Need to implement the name change from ‘Service1’ to ‘ServiceIHaveMade’ here too along with the web.config file.

Before:
<%@ ServiceHost Language="C#" Debug="true" Service="WcfService_Learn.Service1" CodeBehind="ServiceIHaveMade.svc.cs" %>
After:
<%@ ServiceHost Language="C#" Debug="true" Service="WcfService_Learn.ServiceIHaveMade" CodeBehind="ServiceIHaveMade.svc.cs" %>
 

Web.config(partial)

<system.serviceModel>

       <services>

              <service name="WcfService_Learn.ServiceIHaveMade" behaviorConfiguration="WcfService_Learn.ServiceIHaveMadeBehavior">

              <!-- Service Endpoints -->

              <endpoint address="" binding="wsHttpBinding" contract="WcfService_Learn.IService1">

              <!-- Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity automatically. -->

                     <identity>

                           <dns value="localhost"/>

                     </identity>

              </endpoint>

              <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

              </service>

       </services>

       <behaviors>

              <serviceBehaviors>

              <behavior name="WcfService_Learn.ServiceIHaveMadeBehavior">

              <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->

                     <serviceMetadata httpGetEnabled="true"/>

                     <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->

                     <serviceDebug includeExceptionDetailInFaults="false"/>

              </behavior>

              </serviceBehaviors>

       </behaviors>

</system.serviceModel>

November 3, 2009

Generics

Filed under: ASP.NET, All, C# — leoullas @ 8:55 am

Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:

C#

// Declare the generic class
public class GenericList<T>
{
    void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int
        GenericList<int> list1 = new GenericList<int>();

        // Declare a list of type string
        GenericList<string> list2 = new GenericList<string>();

        // Declare a list of type ExampleClass
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
    }
}
  • Use generic types to maximize code reuse, type safety, and performance.
  • The most common use of generics is to create collection classes.
  • The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.
  • You can create your own generic interfaces, classes, methods, events and delegates.
  • Generic classes may be constrained to enable access to methods on particular data types.
  • Information on the types used in a generic data type may be obtained at run-time by means of reflection.

//For Interfaces
interface IComparable <T>
//for structs
struct HashBucket <K,D>
//for methods
static void Reverse <T> (T[] arr)
//for delegates
delegate void Action <T> (T arg)

Strongly TYPED & Loosely TYPED

Filed under: ASP.NET, All, C# — leoullas @ 8:49 am

Definition: A strongly typed programming languages is one that requires the type of a variable to be explicitly stated. C is a strongly typed language. You must declare the type of data a variable will store for C to interpret it:

int myVariable;
myVariable = 25;

Perl is a loosely typed language. There is no need to declare the variable type before using it:

$myVariable = 25;
$myVariable = “A String.”;

Basic dode to fetch data from sql server using select statement and put it in dataset using dataadapter

Filed under: ASP.NET, All, C# — leoullas @ 8:42 am
System.Data.SqlClient.SqlConnection objConnection;

System.Data.DataSet objDataSet = new DataSet();

System.Data.SqlClient.SqlDataAdapter objDataAdapter;

objConnection = new SqlConnection("data source=192.168.93.60; uid= tallyman; pwd= tallyman; database=Tallyman");

#region Either of these 2 works

//objDataAdapter = new SqlDataAdapter("Select top 5 id from accounts", "data source=192.168.93.60; uid= tallyman; pwd= tallyman; database=Tallyman");

objDataAdapter = new SqlDataAdapter("Select top 5 id from accounts", objConnection);

#endregion Either of these 2 works

objDataAdapter.Fill(objDataSet, "accountsData");

Console.Write(objDataSet.Tables["accountsData"].Rows.Count);

Console.Read();

October 28, 2009

DropDown List With HardCoded Values with Default Selected a value

Filed under: ASP.NET, All, C# — leoullas @ 10:41 am

There are two ways:

 

Way 1:

In aspx file:

     <td style=”width: 90px; height: 56px;” valign=”middle”>

        <asp:DropDownList ID=”ddlTime” runat=”server” Width=”131px” onchange=”clickClient();”  Height=”19px”>

</asp:DropDownList>

     </td>

In aspx.CS file:

    public static void PopulateDdlTime(DropDownList ddlTime)

    {

        ddlTime.Items.Add(new ListItem(“12:00AM–08:00AM”, “1200AM0800AM”));

        ddlTime.Items.Add(new ListItem(“08:00AM–04:00PM”, “0800AM0400PM”));

        ddlTime.Items.Add(new ListItem(DRISInternatiolization.DRISInternatiolization.GetLabelText(“464″), “Customize”));

        ddlTime.SelectedValue = “0800AM0400PM”;

    }

protected void Page_Load(object sender, EventArgs e)

       {

PopulateDdlTime(ddlTime);

……

……

}

Way 2:

In aspx file:

<td style=”width: 90px; height: 56px;” valign=”middle”>

    <asp:DropDownList ID=”ddlTime” runat=”server” Width=”131px” onchange=”clickClient();” Height=”19px”>

                  <asp:ListItem Value=”1200AM0800AM”>12:00AM–08:00AM</asp:ListItem>

                  <asp:ListItem Value=”0800AM0400PM” Selected=”True”>08:00AM–04:00PM</asp:ListItem>

                  <asp:ListItem Value=”Customize”>Customize…</asp:ListItem>

    </asp:DropDownList>

</td>

Problem: Cant delete after copying FileInfo “The process cannot access the file because it is being used by another process.”

Filed under: ASP.NET, All, C# — leoullas @ 10:34 am

Solution:

You might have not disposed while reading/writing.
Use either of these two:

1.

StreamWriter objStreamWriterUp = null;

TextReader objTextReaderUp = null;

try

{

using (objTextReaderUp = new StreamReader(sourceFilePath)) 

{

using (objStreamWriterUp

= new StreamWriter(destiFilePath, !blIsFirstTimeCl))

{

//your code

}

}

}

catch (Exception ex)

{

throw;

}

finally

{

 

if (objStreamWriterUp != null)

{

                    objStreamWriterUp.Dispose();

}

       }

2.

StreamWriter objStreamWriterUp = null;

TextReader objTextReaderUp = null;

try

{

objTextReaderUp = new StreamReader(sourceFilePath);

objStreamWriterUp = new StreamWriter(destiFilePath, !blIsFirstTimeCl);

//your code

}

catch (Exception ex)

{

throw;

}

finally

{

 

if (objTextReaderUp != null)

{

objTextReaderUp.Dispose();

}

 

if (objStreamWriterUp != null)

{

objStreamWriterUp.Dispose();

}

       }

  

 

ACID

Filed under: All, SQL — leoullas @ 10:10 am

ACID (an acronymn for Atomicity Consistency Isolation Durability) is a concept that Database Professionals generally look for when evaluating databases and application architectures. For a reliable database all this four attributes should be achieved.

  • Atomicity states that database modifications must follow an “all or nothing” rule. Each transaction is said to be “atomic.” If one part of the transaction fails, the entire transaction fails. It is critical that the database management system maintain the atomic nature of transactions in spite of any DBMS, operating system or hardware failure.
  • Consistency states that only valid data will be written to the database. If, for some reason, a transaction is executed that violates the database’s consistency rules, the entire transaction will be rolled back and the database will be restored to a state consistent with those rules. On the other hand, if a transaction successfully executes, it will take the database from one state that is consistent with the rules to another state that is also consistent with the rules.
  • Isolation requires that multiple transactions occurring at the same time not impact each other’s execution. For example, if Joe issues a transaction against a database at the same time that Mary issues a different transaction, both transactions should operate on the database in an isolated manner. The database should either perform Joe’s entire transaction before executing Mary’s or vice-versa. This prevents Joe’s transaction from reading intermediate data produced as a side effect of part of Mary’s transaction that will not eventually be committed to the database. Note that the isolation property does not ensure which transaction will execute first, merely that they will not interfere with each other.
  • Durability ensures that any transaction committed to the database will not be lost. Durability is ensured through the use of database backups and transaction logs that facilitate the restoration of committed transactions in spite of any subsequent software or hardware failures.

January 21, 2009

DateTime Validation using Javascript

Filed under: ASP.NET, All, Javascript — leoullas @ 10:51 am

function Check()

    {

        doOnOff(‘off’);

        var dtStart = document.getElementById(‘<%=txtStartDate.ClientID%>’).value;

           var dtEnd = document.getElementById(‘<%=txtEndDate.ClientID%>’).value;

 

 

           var pos1=dtStart.indexOf(dtCh)

           var strDay1=dtStart.substring(pos1)

           var pos2=dtEnd.indexOf(dtCh)

           var strDay2=dtEnd.substring(pos2)

               if(pos1>2)

               {

                     alert(“The date format should be : mm/dd/yyyy”);

                      return false;

               }

            else if (strDay1.length>8 )

               {

                      alert(“The date format should be : mm/dd/yyyy”);

                      return false;

               }

               else if(pos2>2 )

               {

                     alert(“The date format should be : mm/dd/yyyy”);

                      return false;

               }

            else if (strDay2.length>8 )

               {

                      alert(“The date format should be : mm/dd/yyyy”);

                      return false;

               }

              

               else if (dtEnd.length>10)

               {

                   alert(“The date format should be : mm/dd/yyyy”);

                   return false;

               }

               else if (isDate(dtStart)==false)

               {

            document.getElementById(‘<%=txtStartDate.ClientID%>’).focus();

            return false;

               }

               else if (isDate(dtEnd)==false)

               {

                document.getElementById(‘<%=txtEndDate.ClientID%>’).focus();

                return false;

               }

            else

            {    

                   //check bigger

                   if(Date.parse(dtStart)>0 && Date.parse(dtEnd)>0)

                           {

                         

                       if (Date.parse(dtStart) > Date.parse(dtEnd))    

                            { 

                               alert(‘<%=ShellUtility.GetMessageDetails(“1028″)%>’);                    

                               return false;

                              }

                           else

                                   { 

                                   var diff_date = Date.parse(dtEnd) – Date.parse(dtStart);

                                   if(diff_date > 2592000000)

                                   {

                                       alert(‘<%=ShellUtility.GetMessageDetails(“1027″)%>’);

                                       return false;

                                    }

                                else

                                    {

                                        return true;

                                    }           

                                   }

                           }

                      else

                           {

                            alert(‘<%=ShellUtility.GetMessageDetails(“5027″)%>’);

                            return false;

                           }

                  }

    }

//This Part is to check Date formattings

    var dtCh= “/”;   

//     var constMinYear = 1900;

//  var constMaxYear = 2020;

 

    function isInteger(s){

           var i;

        for (i = 0; i < s.length; i++){  

            // Check that current character is number.

            var c = s.charAt(i);

            if (((c < “0″) || (c > “9″))) return false;

        }

        // All characters are numbers.

        return true;

    }

 

    function stripCharsInBag(s, bag){

           var i;

        var returnString = “”;

        // Search through string’s characters one by one.

        // If character is not in bag, append to returnString.

        for (i = 0; i < s.length; i++){  

            var c = s.charAt(i);

            if (bag.indexOf(c) == -1) returnString += c;

        }

        return returnString;

    }

 

    function daysInFebruary (year){

        // February has 29 days in any year evenly divisible by four,

        // EXCEPT for centurial years which are not also divisible by 400.

        return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );

    }

    function DaysArray(n) {

           for (var i = 1; i <= n; i++) {

                  this[i] = 31;

                  if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}

                  if (i==2) {this[i] = 29;}

       }

       return this;

    }

 

    function isDate(dtStr){

           var daysInMonth = DaysArray(12)

           var pos1=dtStr.indexOf(dtCh)

           var pos2=dtStr.indexOf(dtCh,pos1+1)

           var strMonth=dtStr.substring(0,pos1)

           var strDay=dtStr.substring(pos1+1,pos2)

           var strYear=dtStr.substring(pos2+1)

           strYr=strYear

           if (strDay.charAt(0)==“0″ && strDay.length>1) strDay=strDay.substring(1);

           if (strMonth.charAt(0)==“0″ && strMonth.length>1) strMonth=strMonth.substring(1);

           for (var i = 1; i <= 3; i++) {

                  if (strYr.charAt(0)==“0″ && strYr.length>1) strYr=strYr.substring(1);

           }

           month=parseInt(strMonth);

           day=parseInt(strDay);

           year=parseInt(strYr);

           if (pos1==-1 || pos2==-1){

                  alert(“The date format should be : mm/dd/yyyy”);

                  return false;

           }

           if (strMonth.length<1 || month<1 || month>12){

                  alert(“Please enter a valid month”);

                  return false;

           }

           if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){

                  alert(“Please enter a valid day”);

                  return false;

           }

           if (strYear.length != 4 || year==0 || year<constMinYear || year>constMaxYear){

                  alert(“Please enter a valid 4 digit year between “+constMinYear+” and “+constMaxYear);

                  return false;

           }

           if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){

                  alert(“Please enter a valid date”);

                  return false;

           }

    return true;

    }

ERROR : Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

Filed under: ASP.NET, All — leoullas @ 10:42 am
failed-to-enable-constraints-one-or-more-rows-contain-values-violating-non-null-unique-or-foreign-key-constraints-2

failed-to-enable-constraints-one-or-more-rows-contain-values-violating-non-null-unique-or-foreign-key-constraints-2

1. Chek NULL in database-table and use ISNULL .

2. If there is some column in DataCarrier where AllowDBNull is False, always select that column from SP level whether it is required or not.

failed-to-enable-constraints-one-or-more-rows-contain-values-violating-non-null-unique-or-foreign-key-constraints

failed-to-enable-constraints-one-or-more-rows-contain-values-violating-non-null-unique-or-foreign-key-constraints

SQL error : Conversion failed when converting datetime from character string

Filed under: All, SQL — leoullas @ 10:29 am

 

sql-error-conversion-failed-when-converting-datetime-from-character-string

sql-error-conversion-failed-when-converting-datetime-from-character-string

In case of two THEN conditions of the CASE statement reference expressions of different data types. In this case, SQL Server implicitly converts the data type for the entire CASE expression to the data type in the THEN clause that has the highest order of data-type precedence. (See the SQL Server Books Online (BOL) topic “Data Type Precedence.”)

BEFORE:

declare @SortExpression varchar(20)

set @SortExpression =‘OverSpeed’

 

SELECT        Journey_Id,

                     Drv_ID,

                     Journey_Start_Dt AS ‘StartDateTime’,

                     Journey_End_Dt AS ‘EndDateTime’,

                     Journey_Time_Sec AS ‘TotalTime’,

                     Journey_Dest_Miles AS ‘TotalDistance’,

                     Max_Speed_Mph AS ‘MAXSpeed’,

                     Brake_Flg AS ‘AggDriving’,

                     OverSpeed_Flg AS ‘OverSpeed’

FROM         DRIVER_JOURNEY_INFO AS td

WHERE     (Company_Id = 9003) AND (Drv_ID = 2017) AND (Journey_Start_Dt BETWEEN ‘08/01/2008′ AND ‘09/30/2008′) AND

                      (Journey_End_Dt BETWEEN ‘08/01/2008′ AND ‘09/30/2008′)

ORDER BY

              CASE

                     WHEN @SortExpression = ‘Journey_Id’ THEN Journey_Id

                     WHEN @SortExpression = ‘StartDateTime’ THEN Journey_Start_Dt

                     WHEN @SortExpression = ‘EndDateTime’ THEN Journey_End_Dt

                     WHEN @SortExpression = ‘TotalTime’ THEN Journey_Time_Sec

                     WHEN @SortExpression = ‘TotalDistance’ THEN Journey_Dest_Miles

                     WHEN @SortExpression = ‘MAXSpeed’ THEN Max_Speed_Mph

                     WHEN @SortExpression = ‘AggDriving’ THEN Brake_Flg

                     WHEN @SortExpression = ‘OverSpeed’ THEN OverSpeed_Flg

              ELSE Journey_Id

              END

DESC

CORRECTED:

 

 

ORDER BY

CASE

       WHEN @SortExpression = ‘Journey_Id’ THEN Journey_Id 

       WHEN @SortExpression = ‘StartDateTime’ THEN Journey_Start_Dt 

       WHEN @SortExpression = ‘EndDateTime’ THEN Journey_End_Dt 

       WHEN @SortExpression = ‘TotalTime’ THEN Journey_Time_Sec 

       WHEN @SortExpression = ‘TotalDistance’ THEN Journey_Dest_Miles                                         WHEN @SortExpression = ‘MAXSpeed’ THEN Max_Speed_Mph

       WHEN @SortExpression = ‘TAII’ THEN (CAST(TAI_Time_Sec AS DECIMAL(18,2))/Journey_Time_Sec)*10

       WHEN @SortExpression = ‘TIP’ THEN (CAST(TI_Time_Sec AS DECIMAL(18,2))/Journey_Time_Sec)*100

       WHEN @SortExpression = THEN Journey_Id

       END 

       DESC,

       CASE WHEN @SortExpression = ‘AggDriving’ THEN Brake_Flg END  DESC,

   CASE WHEN @SortExpression = ‘OverSpeed’ THEN OverSpeed_Flg END  DESC

Older Posts »

Blog at WordPress.com.