Total Pageviews

Monday, August 24, 2020

 Updating a hierarchy path


  static void GeneratePath(List<HierarchyNode> all, HierarchyNode current)

        {

            string path = "";

            Action<List<HierarchyNode>, HierarchyNode> GetPath = null;


            GetPath = (List<HierarchyNode> ps, HierarchyNode p) => {

                var parents = all.Where(x => x.HierarchyNodeId == p.ParentNodeId);

                foreach (var parent in parents)

                {

                    path += $"/{ parent.Name}";

                    GetPath(ps, parent);

                }

            };


            GetPath(all, current);

            string[] split = path.Split(new char[] { '/' });

            Array.Reverse(split);


            current.Path = string.Join(" > ", split) + current.Name;

        }

Tuesday, July 14, 2020

Flatten tree view data

//Nested tree list, result list contains list of lists
 List<NavigationItem> allitems= result;

//Flatten the list
 List<NavigationItem> childitems = Flatten(allitems, a=>a.Items).ToList();


   public  List<NavigationItem> Flatten(List<NavigationItem> rootLevel, Func<NavigationItem, List<NavigationItem>> nextLevel)
        {
            List<NavigationItem> accumulation = new List<NavigationItem>();
            int i = 0;
            flattenLevel(accumulation, rootLevel, nextLevel, i);
            return accumulation;
        }

     
        private  void flattenLevel(List<NavigationItem> accumulation, List<NavigationItem> currentLevel, Func<NavigationItem, List<NavigationItem>> nextLevel, int level)
        {
            level++;

            foreach (NavigationItem item in currentLevel)
            {
             
                item.LevelNo = level;
                item.Level = "Level " + level.ToString();
                accumulation.Add(item);
                flattenLevel(accumulation, nextLevel(item), nextLevel, level);
            }
        }

Wednesday, July 1, 2020

Loading Treeview fast

Func<Employee, int> getXId = (x => x.EmployeeId);
Func<Employee, int?> getXParentId = (x => x.ManagerId);
Func<Employee, string> getXDisplayName = (x => x.Name);
LoadListItems(employees, getXId, getXParentId, getXDisplayName);

 private void LoadListItems<T>(IEnumerable<T> items, Func<T, int> getId, Func<T, int?> getParentId, Func<T, string> getDisplayName)
        {
            dicNodeList.Clear();

            var result = new List<NavigationItem>();

            foreach (var item in items)
            {
                var id = getId(item);
                var displayName = getDisplayName(item);
                var node = new NavigationItem { ID = id, Name = displayName, NodeInfo = item };
                node.Items = new List<NavigationItem>();
                dicNodeList.Add(getId(item), node);

            }

            foreach (var id in dicNodeList.Keys)
            {
                var currentNode = GetXNode(id);
                var nodeInfo = (T)currentNode.NodeInfo;
                var parentNodeID = getParentId(nodeInfo);

                if (parentNodeID.HasValue && dicNodeList.ContainsKey(parentNodeID.Value))
                {
                    var parent= GetXNode(parentNodeID.Value);
                    parent.Items.Add(currentNode);

                }
                else
                {
                    result.Add(currentNode);
                }
            }


            var z = result;

        }

public NavigationItem GetXNode(int id)
{
            return dicNodeList[id];
}

 Dictionary<int, NavigationItem> dicNodeList = new Dictionary<int, NavigationItem>();


 public class NavigationItem
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int? ParentID { get; set; }
        public List<NavigationItem> Items { get; set; }
        public object NodeInfo { get; set; }

    }


Sunday, April 2, 2017

Updating site http to https

Add HTTP response header as below on IIS

Content-Security-Policy : upgrade-insecure-requests

Above will treat http request as secured.

Add a rule as below between <rules></rules> section

<rule name="HTTP to HTTPS redirect" stopProcessing="true">
  <match url="(.*)" />
    <conditions>
      <add input="{HTTPS}" pattern="off" ignoreCase="true" />
    </conditions>
  <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
</rule>

Monday, March 13, 2017

Getting IIS hosted web site's information

VBScript will fetch IIS web site's information. Just download and double click to run, a text file will be created with necessary information.

https://drive.google.com/open?id=0B8R1wPP0Gj58SDFTUjlhdWk2Um8



Monday, February 13, 2017

.Getting .NET framework versions

Go to CMD

This will display framework version

cmd:\> reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\full" /v version

Monday, October 19, 2015

Uploading fles to specific folder on BOX

Refresh token is over written on each request and store on text file.


 Function UploadToBox(ByVal attachedFilename As String, ByVal stream As System.IO.Stream) As Boolean

        Dim clientID As String
        Dim clientSecret As String
        Dim oldRefreshToken As String
        Dim newToken As BoxApi.V2.Authentication.OAuth2.OAuthToken

        clientID = ConfigurationManager.AppSettings("clientid")
        clientSecret = ConfigurationManager.AppSettings("clientsecret")

        Dim tokenProvider As New TokenProvider(clientID, clientSecret)

        '''' Reading Refresh token from the file
        Dim streamReader As StreamReader
        streamReader = System.IO.File.OpenText(Server.MapPath("~\\Box\\BoxApiRefreshToken.txt"))
        oldRefreshToken = streamReader.ReadToEnd()
        streamReader.Close()

        newToken = tokenProvider.RefreshAccessToken(oldRefreshToken)
        Dim boxManager As New BoxManager(newToken.AccessToken)

        '''' Writing the new Refresh token to the file
        Dim streamWriter As New StreamWriter(Server.MapPath("~\\Box\\BoxApiRefreshToken.txt"))
        streamWriter.Write(newToken.RefreshToken)
        streamWriter.Close()

        Dim uploadFolder As Folder

        ''''rootFolder = boxManager.GetFolder(Folder.Root)
        uploadFolder = boxManager.GetFolder(ConfigurationManager.AppSettings("uploadFolderID"))

        Dim fileName As String
        fileName = System.IO.Path.GetFileNameWithoutExtension(attachedFilename)
        fileName = fileName + "-" + Guid.NewGuid.ToString + System.IO.Path.GetExtension(attachedFilename)

        boxManager.CreateFile(uploadFolder, fileName, ConvertStreamToByteArray(stream))


    End Function
Convert stream to byte array
    Private Function ConvertStreamToByteArray(ByVal stream As System.IO.Stream) As Byte()

        Dim streamLength As Long = Convert.ToInt64(stream.Length)
        Dim fileData As Byte() = New Byte(streamLength) {}
        stream.Position = 0
        stream.Read(fileData, 0, streamLength)
        stream.Close()

        Return fileData

    End Function

Getting Salesforce session ID

Put the post request on XML files

 Function GetSalesForceSessionID() As String

        Dim SID As String = String.Empty

        Dim AllowUploadSalesforce As String

        AllowUploadSalesforce = ConfigurationManager.AppSettings("allowUploadSalesforce").ToLower()

        If AllowUploadSalesforce = "true" Then

            '''' Loading XML Data
            Dim XMLDoc As New StreamReader(Me.Server.MapPath("~") + "/XMLTemplates/WestpacCredentials.xml")

            '''' Transform XML data to byte array
            Dim XMLData As String
            XMLData = XMLDoc.ReadToEnd()
            Dim PostData As Byte() = Encoding.UTF8.GetBytes(XMLData)

            '''' Post XML data to Salesforce
            Dim WClient As New WebClient
            WClient.Headers.Add("SOAPAction", "login")
            WClient.Headers.Add("Content-Type", "text/xml; charset=utf-8")

            Dim OutPutData As Byte()

            Try
                OutPutData = WClient.UploadData(ConfigurationManager.AppSettings("SFEndPoint"), "POST", PostData)

                '''' Reading the the response
                Dim XMLOutPut As String
                XMLOutPut = WClient.Encoding.GetString(OutPutData)

                '''' Transform XML string to XML document
                Dim XMLOutputDoc As New XmlDocument
                XMLOutputDoc.LoadXml(XMLOutPut)

                Dim root As XmlElement
                root = XMLOutputDoc.DocumentElement

                '''' Reading SessionID from xml
                SID = root("soapenv:Body")("loginResponse")("result")("sessionId").InnerText

            Catch ex As Exception

                SID = String.Empty
                Me.SendServiceError(ex.ToString())

            End Try

            WClient.Dispose()
        End If

        Return SID

    End Function

Validate on lost focus

On the Page_Load

txtFirstNameStep0.Attributes.Add("onblur", "ValidatorOnChange(event);")

Disable multiple button clicks

Call on the Page_Load

 PreventMultipleClicksforContinue(ibContinueStep0)

Below method adds JAVAScript code to the on click event

    Public Shared Sub PreventMultipleClicksforContinue(ByRef button As System.Web.UI.WebControls.Button)
        button.Attributes.Add("onclick", "if (Page_ClientValidate()) { this.disabled=true;}" & button.Page.ClientScript.GetPostBackEventReference(button, String.Empty).ToString)
    End Sub

Thursday, September 3, 2015

Converting an Object to XML format and put on stream

Following code accept the object and convert to XML, then content will be transformed to memory stream.

 Dim currentStream As New MemoryStream()
  Dim streamWriter As New StreamWriter(currentStream)
  streamWriter.Write(CreateXMLDoc(reportDetail))

  streamWriter.Flush()
  currentStream.Position = 0

reportDetail is the object to pass to pass CreatXMLDoc

 Public Shared Function CreateXMLDoc(ByVal value As Object) As String
        Dim rv As String = ""
        Dim xml = New XmlSerializer(value.[GetType]())
        Using memoryStream As MemoryStream = New MemoryStream()

            Using xmlWriter As XmlTextWriter = New XmlTextWriter(memoryStream, Encoding.UTF8)
                xmlWriter.Formatting = Formatting.Indented
                xml.Serialize(xmlWriter, value)
                rv = Encoding.UTF8.GetString(memoryStream.ToArray())
            End Using

        End Using
        Return rv
    End Function

Wednesday, July 29, 2015

Adding text to existing PDFusing iTextSharp

Sample text is added to every page on the same location

Inside the Page_Load()

                    string filepath = @"http://EXAMPLE.COM/TEST.pdf";
       
                    // open the reader
                    PdfReader reader = new PdfReader(filepath);
                    Rectangle size = reader.GetPageSizeWithRotation(1);
                    Document document = new Document(size);

                    // open the writer
                    //FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);    
                    MemoryStream fs = new MemoryStream();
                    PdfWriter writer = PdfWriter.GetInstance(document, fs);
                    document.Open();

                    PdfContentByte cb = writer.DirectContent;

                    int pageCount = reader.NumberOfPages;

                    var rectangle = reader.GetPageSize(1);


                    for (int i = 1; i <= pageCount; i++)
                    {
                        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                        cb.SetColorFill(Color.BLACK);
                        cb.SetFontAndSize(bf, 9);

                        cb.BeginText();

                        cb.ShowTextAligned(2, "This is the new Text " , 535, 33, 0);
                        cb.EndText();

                        PdfImportedPage page = writer.GetImportedPage(reader, i);

                        var widthFactor = document.PageSize.Width / page.Width;
                        var heightFactor = document.PageSize.Height / page.Height;
                        var factor = Math.Min(widthFactor, heightFactor);

                        var offsetX = (document.PageSize.Width - (page.Width * factor)) / 2;
                        var offsetY = (document.PageSize.Height - (page.Height * factor)) / 2;
                        cb.AddTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
                        document.NewPage();
                    }

                    document.Close();
                    fs.Close();
                    writer.Close();
                    reader.Close();

                    WebClient client = new WebClient();

                    Byte[] buffer = fs.GetBuffer();

                    if (buffer != null)
                    {
                        Response.ContentType = "application/pdf";
                        Response.AddHeader("content-length", buffer.Length.ToString());
                        Response.BinaryWrite(buffer);
                        Response.Flush();

                    }

Wednesday, July 1, 2015

Root domain redirections


Following will redirect the root domain only, not the pages,

www.test.com > www.example.com - this will redirect
www.test.com/default.aspx > this will not redirect

<rewrite>
            <rules>
  <rule name="Root Redirect" enabled="true" stopProcessing="true">
                    <match url="^$" />
                    <action type="Redirect" url="https://www.example.com/" />
                </rule>

            </rules>
 </rewrite>

Wednesday, November 26, 2014

Adding custom extension (.SEO) to the URL

Add the handler mapping to IIS

 <handlers>
            <add name="*.seo-4.0_32Bit" path="*.seo" verb="*" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" preCondition="classicMode,runtimeVersionv4.0,bitness32" />
 </handlers>

If extension not worked, add following between <system.webServer>

<modules runAllManagedModulesForAllRequests="true" >
<remove name="UrlRoutingModule"/>
</modules>

Wednesday, November 19, 2014

Redirections using Web.config

Page redirections for different domain

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   
<location path="hydro-burn">
      <system.webServer>
        <httpRedirect enabled="true" destination="http://www.example.com.au/hydro-burn" httpResponseStatus="Permanent" />
      </system.webServer>
    </location>

<location path="hydro-whey">
      <system.webServer>
        <httpRedirect enabled="true" destination="http://www.example.com.au/hydro-whey" httpResponseStatus="Permanent" />
      </system.webServer>
    </location>

<location path="amino-fuel">
      <system.webServer>
        <httpRedirect enabled="true" destination="http://www.example.com.au/amino-fuel" httpResponseStatus="Permanent" />
      </system.webServer>
    </location>

</configuration>

Domain redirections

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpRedirect enabled="true" destination="http://www.example.com.au" exactDestination="true" httpResponseStatus="Permanent" />
    </system.webServer>
</configuration>

Tuesday, November 4, 2014

Adding mask using Jquery

<script language="javascript" src="../../js/jquery.maskedinput.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {

      //Input mask for ABN
        $('#txtABNstep1').mask('?ABN 99 999 999 999');

        //Input mask for Contact number      
        $('#txtContactNumberStep1').mask('(99) 9999-9999');

        //Input mask for Contact mobile phone
        $('#txtMobileNumberStep1').mask('9999999999');


});

Monday, November 3, 2014

Regex for http, https or www

(http(s)?://)?([\w-]+\.)+[\w-]+[.com]+(/[/?%&=]*)?

Monday, July 28, 2014

Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option

Run below inside the database

sp_configure 'clr enabled',1
GO
RECONFIGURE
GO
sp_configure 'clr enabled'  -- make sure it took
GO

Sunday, July 13, 2014

Accessing parent frames using JQuery

   $(function () {
            $(window).load(function () {
                var frame = window.parent.$('frame[name="frmFrame"]')[0].contentDocument;
                if ($(frame).find('.classname').is(':visible')) {
                        //Do something
                }
                else {
                     //Do something
                }

            })
        })

HTTP to HTTPS Redirect using Rewrite module

Rule to redirect to HTPS, Illustrated domain is treated as www.yourdomain.com.au, if is www.yourdomain.com the pattern will be pattern="^www\.yourdomain\.com$"

     <rule name="Redirect to HTTPS" enabled="true" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                        <add input="{HTTP_HOST}" pattern="^www\.yourdomain.com\.au$" />
                        <add input="{HttpsRedirects:{REQUEST_URI}}" pattern="(.+)" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{C:1}" appendQueryString="false" redirectType="SeeOther" />
                </rule>

Pages which are to be redirect, Page ending .aspx and extention less are considered.

  <rewriteMaps>
                <rewriteMap name="HttpsRedirects">
                    <add key="/content_common/application.aspx" value="/content_common/application.aspx" />
                    <add key="/content_common/application" value="/content_common/application" />
</rewriteMap>
</rewriteMaps>