Total Pageviews

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>