Friday 30 March 2012

Create XML Document using linq and with out using Linq....

The XML part

Now that we have an understanding of LINQ, it's time to move on to the XML part.
For this article, we will be using this XML file:


<?xml version="1.0" encoding="utf-8" ?>
<employees>
   <employee id="1" salaried="no">
      <name>Gustavo Achong</name>
      <hire_date>7/31/1996</hire_date>
   </employee>
   <employee id="3" salaried="yes">
      <name>Kim Abercrombie</name>
      <hire_date>12/12/1997</hire_date>
   </employee>
   <employee id="8" salaried="no">
      <name>Carla Adams</name>
      <hire_date>2/6/1998</hire_date>
   </employee>
   <employee id="9" salaried="yes">
      <name>Jay Adams</name>
      <hire_date>2/6/1998</hire_date>
   </employee>
</employees> 
 
 

The old way

In the previous versions of the .NET Framework, XML was document-centric; in other words, to create any structure, you first had to start with an XMLDocument.

The new way

Using the classes from the System.Xml.Linq namespace and the features available in .NET 3.5, constructing an XML document is very easy and very readable.
Constructing a document in this way is possible because of the functional construction feature in LINQ to XML. Functional construction is simply a means of creating an entire document tree in a single statement.
 
public XElement(XName name, Object[] content)
 
As we can see from one of the constructors for XElement, it takes an array of objects. In the example above, the employees element is constructed from four XElements, one for each employee, which in turn is constructed from XAttributes and other XElements.
In the above example, we could have replaced XDocument with XElement if we removed the XDeclaration and XComment objects. This is because the constructor XDocument used takes a XDeclaration instance, rather than the XName that the XElement constructor takes.


public XDocument(XDeclaration declaration,Object[] content) 
 
Another thing to note when running the demo is how both documents are printed to the console window.

As we can see, the old method just streams the contents of the document to the console. The method does that also; however, it is nicely formatted with no extra effort.

For Reference Visit..... 
 

Thursday 29 March 2012

Telerik web.config Settings

Telerik Rich Text Editor and ASP.NET MVC

The good people at Telerik have been kind enough to integrate their UI controls with the ASP.NET MVC framework so that we don't have to go without glorious and essential features like spell checking and paste-from-word. Their website does provide guidance for doing this, however I found that their instructions don't quite work so I will post my own. These instructions cover the text editor but the other controls should be similar. I won't go though everything, just the bits that Telerik left out, so make sure you read the official documentation.

Install the Telerik RAD controls

That name bugs me. They might as well have called it the 'like-cowabunga-narly-rad-fully-awesome-mega-xp-titanium-control-suite'. If, like me, you don't fancy running a 300M installer you can instead download  a zip and manually copy the files you need. I recommend this approach since it terns out you only need one file.

Add a Reference to Telerik.Web.UI.dll

All that is required is to add a reference from your MVC project to the Telerik.Web.UI.dll. Here is the first place where the telerik documentation let me down. They say to reference the dll in the bin directory but if you are using .NET 3.5 then you need to reference the dll in the bin35 directory.

Add some things to Web.config

Read the instructions and add the required handlers to web.config. If you want the editors dialog boxes to work then you must also add a http handler for that. The changes to the web.config are:
1.<httpHandlers>
2....
3.<add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false" />
4.<add path="Telerik.Web.UI.DialogHandler.axd" verb="*" type="Telerik.Web.UI.DialogHandler" validate="false" />
5.</httpHandlers>
1.<handlers>
2....
3.<add name="Telerik_Web_UI_WebResource_axd" verb="*" preCondition="integratedMode" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" />
4.<add name="Telerik_Web_UI_DialogHandler_axd" verb="*" preCondition="integratedMode" path="Telerik.Web.UI.DialogHandler.axd" type="Telerik.Web.UI.DialogHandler" />
5.</handlers>
If you add the editor control to an mvc partial then you must include the rad stylesheet manager and rad script manager in the partial. You must also include the rad script manager in the view that includes the partial. Weird I know. Here is an example of what the partial might look like:
01.<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
02.<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
03.<telerik:RadScriptManager ID="scriptmanager2" runat="server"></telerik:RadScriptManager>
04. 
05.<%
06.editor.Content = Model.Content;
07.%>
08.<telerik:RadStyleSheetManager ID="stylesheetmanager" runat="server" ></telerik:RadStyleSheetManager>
09.<telerik:RadEditor runat="server" ID="editor" DialogHandlerUrl="~/Telerik.Web.UI.DialogHandler.axd"  />
10.</div>

For Reference .....

=========================================================================

Tuesday 27 March 2012

LinQ Using Substring

Dim result1() As String = txtBody.Text.Trim.Split("<")
            Dim result2 = (From te In result1 Where te.Contains("@HTMLRemovalURL@") Select te).ToList
'Out Put of Above Statement is  " a href=" http://sparsh180/easyshop2008/@HTMLRemovalURL@" > "
          Dim  originalString  As String =  result2(0).Remove(0, 1)
'Out Put of Above Statement is  " href=" http://sparsh180/easyshop2008/@HTMLRemovalURL@" > "

If originalString.ToLower().Contains(SystemSettingsBO.GetSettings("BusinessWebAddress").ToLower()) Then
                Dim result3 = (From te In result1 Where te.Contains("@HTMLRemovalURL@") Select " href=""" + te.Substring(te.IndexOf("@"))).ToList
'Out Put of Above Statement is  " href=" http://@HTMLRemovalURL@ "  "

     Dim  replacedString  As String  =  result3(0)

       If bodytext.Contains(originalString) Then
           bodytext = bodytext.Replace(originalString, replacedString)
       End If

      txtBody.Text = bodytext
 End If

Find Previous & Present browsing urls & IP Address , Browser Type & Browser Version.....

Previous URL  : http://yahoo/default.aspx

Present URL : http://yahoo/Home.aspx


Request.UrlReferrer.AbsoluteUri  it gives Previous URL i.e ( http://yahoo/Home.aspx )

Request.Url.AbsolutePath it gives Present URL i.e ( http://yahoo/default.aspx )

Request.ServerVariables("REMOTE_ADDR") it gives IP Address of the user Like (190.10.250.55)

HttpContext.Current.Request.Browser.Type it gives Browser type i.e IE,Firefox....(Firefox11.0)

HttpContext.Current.Request.Browser.Version it gives Browser Version Like( 11.0 )



Monday 26 March 2012

Display Popup for some time & auto hide that popup after specified time...

If Not Session("IsimgAddToCart") Is Nothing Then 'Added by Team7e for Popup Issue.
                If Session("IsimgAddToCart") = "yes" Then
               ScriptManager.RegisterClientScriptBlock(Page, Me.GetType(), "MyScript", "startPopup()", True)
                    Session("IsimgAddToCart") = "no"
                Else
                    Session("IsimgAddToCart") = "no"
                End If
            End If
=======================================================

<%--This is for popup Issue.--%>
   <script type='text/javascript'>
        function closeMyPopup() {
            document.getElementById("ctl00_pnlviewcart").style.display = "none";
        }

        function myPopupRelocate() {
            var scrolledX, scrolledY;
            if (self.pageYOffset) {
                scrolledX = self.pageXOffset;
                scrolledY = self.pageYOffset;
            } else if (document.documentElement && document.documentElement.scrollTop) {
                scrolledX = document.documentElement.scrollLeft;
                scrolledY = document.documentElement.scrollTop;
            } else if (document.body) {
                scrolledX = document.body.scrollLeft;
                scrolledY = document.body.scrollTop;
            }

            var centerX, centerY;
            if (self.innerHeight) {
                centerX = self.innerWidth;
                centerY = self.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) {
                centerX = document.documentElement.clientWidth;
                centerY = document.documentElement.clientHeight;
            } else if (document.body) {
                centerX = document.body.clientWidth;
                centerY = document.body.clientHeight;
            }

            var leftOffset = scrolledX + (centerX - 250) / 2;
            var topOffset = scrolledY + (centerY - 200) / 2;

            document.getElementById("ctl00_pnlviewcart").style.top = topOffset + "px";
            document.getElementById("ctl00_pnlviewcart").style.left = leftOffset + "px";
        }
        function startPopup() {
                window.setTimeout("fireMyPopup()", 500);
        }
        function fireMyPopup() {
            myPopupRelocate();
            document.getElementById("ctl00_pnlviewcart").style.display = "block";
            document.body.onscroll = myPopupRelocate;
            window.onscroll = myPopupRelocate;
            window.setTimeout("closeMyPopup()", 5000);
        }
//        document.body.onload = window.setTimeout("fireMyPopup()", 500);
    </script>

Monday 19 March 2012

Remove Whitespace & Duplicate Records depending on primary key & Remove Special Characters


Remove Whitespace

Public Shared Function RemoveWhitespace(ByVal str As String) As String
        Try
            Return New Regex("\s*").Replace(str, String.Empty)
        Catch generatedExceptionName As Exception
            Return str
        End Try
    End Function
==========================================================================
Remove Duplicates

If ds.Tables(0).Rows.Count > 0 Then
                Dim dt As New DataTable()
                dt = RemoveDuplicates(ds.Tables(0))
                ds.Tables.Clear()
                ds.Tables.Add(dt)
End If

Shared Function RemoveDuplicates(ByVal dt As DataTable) As DataTable
   Return ( _
    From row In dt.Rows.OfType(Of DataRow)() _
     Group row By GroupKey = row.Field(Of Int64)("PKProductID") Into g = Group _
     Select g.OrderBy(Function(r) r.Field(Of Int64)("PKProductID")).First()).CopyToDataTable()

End Function
--------------------- ( OR ) -----------------------------------

Public Shared Function RemoveDuplicateStores(ByVal dTable As DataTable, ByVal colName As String) As DataTable

        Dim hTable As New Hashtable()
        Dim duplicateList As New ArrayList()

        'Add list of all the unique item value to hashtable, which stores combination of key, value pair.  
        'And add duplicate item value in arraylist.   

        For Each drow1 As DataRow In dTable.Rows
            If hTable.Contains(drow1(colName)) Then
                duplicateList.Add(drow1)
            Else
                hTable.Add(drow1(colName), String.Empty)
            End If
        Next

        'Removing a list of duplicate items from datatable.  
        For Each drow2 As DataRow In duplicateList
            dTable.Rows.Remove(drow2)
        Next

        'Datatable which contains unique records will be return as output.     
        Return dTable
End Function

=======================================================

''' <summary>
    '''  This funcation escape the some characters
    ''' </summary>
    ''' <param name="tempQuery"></param>
    ''' <returns name="return the query string without parmeters"></returns>
    ''' <remarks></remarks>

Public Shared Function RemoveSpecialCharacters(ByVal tempQuery As String) As String
        tempQuery = tempQuery.ToLower
        Dim strEscape() As String = {"#", """", "&quot;", "\u0022", "&apos;", "\u0027", "&", "\u0026", "<", "&lt;", "\u003c", ">", "&gt;", "\u003e", "'"}
        For Each s As String In strEscape
            tempQuery = tempQuery.Replace(HttpUtility.UrlEncode(s), "")
        Next
        tempQuery = tempQuery.Replace("""", "")
        tempQuery = tempQuery.Replace("%27", "")
        Return tempQuery
End Function


Sunday 18 March 2012

SQL SERVER HELP



Get All User Defined Stored Procedures List

It gives only SpNames

SELECT  DISTINCT(sysobjects.name)
                FROM
                        sysobjects,syscomments
                WHERE
                        sysobjects.id =     syscomments.id
                AND
                        sysobjects.type = 'P'
                AND
                        sysobjects.category=0

(OR)

It gives SpNames and also Defination

select * from sysobjects where type='p'


Get specific word used in User Defined Stored Procedures List

It gives only SpNames
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(object_id) LIKE '%SELECT * FROM Category WHERE PKCategoryID = @PKCategoryID%'

(OR)
It gives SpNames and also Defination

select object_name(o.object_id), m.*
from sys.sql_modules m
join sys.objects o on m.object_id = o.object_id
where o.type= 'P'
and m.definition like N'%SELECT * FROM Category WHERE PKCategoryID = @PKCategoryID%'


Get All Databases Names
SELECT *
FROM sys.Databases


Get All Tables Names
SELECT *
FROM sys.Tables

(OR)
select * from sysobjects where type='U' order by name

This will gives the exact user tables from database

SELECT * FROM sysobjects
WHERE
type='U'
and
name != 'dtproperties'
ORDER BY [name]

This Querry to show the all column count from a Specific Table

SELECT COUNT(*)
FROM EasyShopJuJuBe_new_29July2011.sys.columns
WHERE object_id = OBJECT_ID('EasyShopJuJuBe_new_29July2011.dbo.Category')


This Querry to fetch all functions(userdefined or system) in a database:

select * from sysobjects where type='fn'

This Querry to fetch all (Tables Names,columnNames,Datatype and Size) in a database:

SELECT SysObjects.[Name] as TableName, SysColumns.[Name] as ColumnName,
SysTypes.[Name] As DataType,SysColumns.[Length] As Length FROM SysObjects INNER JOIN SysColumns
ON SysObjects.[Id] = SysColumns.[Id] INNER JOIN SysTypes ON SysTypes.[xtype] = SysColumns.[xtype]
WHERE SysObjects.[type] = 'U' ORDER BY SysObjects.[Name]

This Querry to find All Triggers in a database:

select * from sysobjects where type='tr'

(OR)

select * from sys.triggers

Saturday 17 March 2012

Catch a Error log and write that error as Xml File

Try
          ErrorLog.Log("Price is coming as empty for product in Viewcart " & i.Split(",")(i.Split(",").Length - 1) & " " & HttpContext.Current.Request.Cookies("pgid").Value, Nothing)

.................
Catch ex As Exception
            ErrorLog.XMLError("GetFaceBookCode()", ex, False, "Error Occured in GetFaceBookCode() method")
End Try

========================================================================
Imports System.Web.Mail
Imports System.Web
Imports System.Web.HttpContext
Imports System.Configuration
Imports System.IO
Imports System.Xml
Imports GotDotNet.Elmah

Public Enum MessageType
  Trace = 1
  Log
End Enum
'Note: We need to define few keys in appSettings section in Web.config.
'Note: ErMsg is added to send the
Public Class ErrorLog

    Shared BrowserInfo As String = String.Empty
    Public Shared Sub XMLError(ByVal FunctionName As String, ByVal Er As Exception, Optional ByVal isEmail As Boolean = True, Optional ByVal ErMsg As String = "")
        Try
            If Er.Message.Contains("Thread was being aborted") Then
                Return
            End If
            Dim dirErrorLog As New DirectoryInfo(HttpContext.Current.Server.MapPath("~/ErrorLogs"))
            If Not dirErrorLog.Exists Then
                dirErrorLog.Create()
            End If
            If File.Exists(HttpContext.Current.Server.MapPath("~/ErrorLogs/Error-") & Format(Now, "yyyyMMdd") & ".xml") Then
                ErrorElementsName(Er, ErMsg)
            Else
                Dim writer As New XmlTextWriter(HttpContext.Current.Server.MapPath("~/ErrorLogs/Error-") & Format(Now, "yyyyMMdd") & ".xml", Nothing)
                writer.WriteStartDocument()
                writer.WriteStartElement(Nothing, "Errors", Nothing)
                writer.WriteEndElement()
                writer.WriteEndDocument()
                writer.Close()
                ErrorElementsName(Er, ErMsg)
            End If
            If isEmail Then
                Try
                    'Dim errorMail As Hashtable = ConfigurationManager.GetSection("gotdotnet.elmah/errorMail")
                    'Dim err As New GotDotNet.Elmah.Error(Er, HttpContext.Current)
                    'Dim strw As New StringWriter()
                    'Dim formatter As New GotDotNet.Elmah.ErrorMailHtmlFormatter()
                    'Dim strBody As String = strw.ToString()
                    'GotDotNet.Elmah.ErrorLog.Default.Log(err)
                    'formatter.Format(strw, err)
                    'strBody = strBody.Replace(vbCrLf, "")
                    'strBody = strBody.Replace(vbCr, "")
                    'strBody = strBody.Replace(vbLf, "")
                    Dim errorMail As Hashtable = ConfigurationManager.GetSection("gotdotnet.elmah/errorMail")
                    Dim err As New GotDotNet.Elmah.Error(Er, HttpContext.Current)
                    GotDotNet.Elmah.ErrorLog.Default.Log(err)
                    Dim strw As New StringWriter()
                    Dim formatter As New ErrorMailHtmlFormatter()
                    formatter.Format(strw, err)
                    Dim strBody As String = strw.ToString()
                    strBody = strBody.Replace(vbCrLf, "")
                    strBody = strBody.Replace(vbCr, "")
                    strBody = strBody.Replace(vbLf, "")
                    EmailUtil.SendMail(errorMail("from"), errorMail("to"), "", "", Rebex.Mail.MailPriority.High, err.Message.Replace("\r", " ").Replace("\n", " "), MailFormat.Html, strBody, "")
                Catch
                End Try
            End If
        Catch ex As Exception
        End Try
    End Sub
    Public Shared Sub Log(ByVal Er As String, ByVal MType As MessageType)
        'Try
        Dim dirErrorLog As New DirectoryInfo(HttpContext.Current.Server.MapPath("~/ErrorLogs"))
        If Not dirErrorLog.Exists Then
            dirErrorLog.Create()
        End If
        If File.Exists(HttpContext.Current.Server.MapPath("~/ErrorLogs/Log-") & Format(Now, "yyyyMMdd") & ".xml") Then
            LogElementsName(MType, Er)
        Else
            Dim writer As New XmlTextWriter(HttpContext.Current.Server.MapPath("~/ErrorLogs/Log-") & Format(Now, "yyyyMMdd") & ".xml", Nothing)
            writer.WriteStartDocument()
            writer.WriteStartElement(Nothing, "Logs", Nothing)
            writer.WriteEndElement()
            writer.WriteEndDocument()
            writer.Close()
            LogElementsName(MType, Er)
        End If

        'Catch ex As Exception
        'End Try
    End Sub
    Private Shared Sub ErrorElementsName(ByVal er As Exception, Optional ByVal ErMsg As String = "")
        'Added by Team7e for Issue#1519.
        BrowserInfo = "The browser type : " & HttpContext.Current.Request.Browser.Type & ", browser version : " & HttpContext.Current.Request.Browser.Version & "  and IP Address : " & HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")

        Dim doc As New XmlDocument
        doc.Load(HttpContext.Current.Server.MapPath("~/ErrorLogs/Error-" & Format(Now, "yyyyMMdd") & ".xml"))

        Dim el As XmlElement
        Dim passPhrase As String = "Ecommerce1CrAp5"
        Dim initVector As String = "@4B2c2E4e4F6g2326"
        Dim rijndaelKey As Rijndael = New Rijndael(passPhrase, initVector, 128, 0, 256)

        el = doc.CreateElement("Error")
        doc.DocumentElement.AppendChild(el)
        CreateChildElement(doc, "Error_Logged_On", Now.ToString, el)
        'CreateChildElement(doc, "Function_Name", FunctionName, el)
        'CreateChildElement(doc, "Error_Message", er.Message + ErMsg, el)
        CreateChildElement(doc, "Error_Message", rijndaelKey.Encrypt(er.Message + ErMsg), el)

        'Added by Team7e for Issue#1519.
        CreateChildElement(doc, "Browser_Info", BrowserInfo, el)


        'Return rijndaelKey.Encrypt(PlainText)
        CreateChildElement(doc, "Stack_Trace", rijndaelKey.Encrypt(er.StackTrace), el)
        'CreateChildElement(doc, "Stack_Trace", er.StackTrace, el)
        doc.Save(HttpContext.Current.Server.MapPath("~/ErrorLogs/Error-" & Format(Now, "yyyyMMdd") & ".xml"))
    End Sub
    Private Shared Sub LogElementsName(ByVal MType As MessageType, ByVal er As String)
        Dim doc As New XmlDocument
        doc.Load(HttpContext.Current.Server.MapPath("~/ErrorLogs/Log-" & Format(Now, "yyyyMMdd") & ".xml"))
        Dim el As XmlElement
        el = doc.CreateElement("Log")
        doc.DocumentElement.AppendChild(el)
        CreateChildElement(doc, "Logged_On", Now.ToString, el)
        'CreateChildElement(doc, "Function_Name", FunctionName, el)
        If MType = MessageType.Trace Then
            CreateChildElement(doc, "Type", "Trace", el)
        ElseIf MType = MessageType.Log Then
            CreateChildElement(doc, "Type", "Log", el)
        End If
        CreateChildElement(doc, "Message", er, el)
        doc.Save(HttpContext.Current.Server.MapPath("~/ErrorLogs/Log-" & Format(Now, "yyyyMMdd") & ".xml"))
    End Sub
    Private Shared Sub CreateChildElement(ByVal doc As XmlDocument, ByVal ElName As String, ByVal Text As String, ByVal el As XmlElement)
        Dim el1 As XmlElement = doc.CreateElement(ElName)
        el1.InnerText = Text
        el.AppendChild(el1)
    End Sub
    Private Shared Function GetTodayDate() As String
        Return Now.Year.ToString & "_" & Now.Month.ToString & "_" & Now.Day.ToString
    End Function
End Class
=======================================================================
Error Log OutPut..... in the file of  "Error-20120317.xml"

  <?xml version="1.0" ?>
- <Errors>
- <Error>
  <Error_Logged_On>3/17/2012 3:24:44 PM</Error_Logged_On>
  <Error_Message>Access to the path 'E:\Source\TFS\AIMSEasyShop\EasyShop2008Solution\EasyShop2008\App_Themes\Generic\style.css' is denied.</Error_Message>
  <Browser_Info>The browser type : Firefox10.0.2, browser version : 10.0.2 and IP Address : 192.10.250.53</Browser_Info>
  <Stack_Trace>at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) at System.IO.StreamReader..ctor(String path) at System.IO.File.OpenText(String path) at Admin_AllSettings.readCssFile() in E:\Source\TFS\AIMSEasyShop\EasyShop2008Solution\EasyShop2008\Admin\AllSettings.aspx.vb:line 1124 at Admin_AllSettings.Page_Load(Object sender, EventArgs e) in E:\Source\TFS\AIMSEasyShop\EasyShop2008Solution\EasyShop2008\Admin\AllSettings.aspx.vb:line 35</Stack_Trace>
  </Error>
</Errors>
 
==============================================================
 Log OutPut..... in the file of  "Log-20120317.xml"

  <?xml version="1.0" ?>
- <Logs>
- <Log>
  <Logged_On>3/17/2012 12:40:43 PM</Logged_On>
  <Type>Log</Type>
  <Message>Receipt has not been sent to Customer:sadathali2u@yahoo.co.in and Admin:.</Message>
  </Log>
  </Logs>