Monday, 30 November 2015

Upload files on rackspace

Add below configuration of your rackspace in app.config file


 <add key="CloudPath" value="https://147b762764b8984af47e-8da1470f1b1ef4d19e2dd6133421859bf.ssl.cf1.rackcdn.com/" />
    <add key="RackSpaceUserName" value="RackspaceUserName" />
    <add key="RackSpaceAPIKey" value="677ab75crf7d5d8aa74842a6f061da35" />
    <add key="RackSpaceRegion" value="ABC" />
    <add key="Container" value="Images" />

add below methods in class file and call UploadImage method


      public static string UploadImage(string container, string origImageFileName, string imageFullPath)
        {
            string imageFileName, = origImageFileName.ToLower();
            try
            {

                string region = string.IsNullOrEmpty(ConfigurationManager.AppSettings["RackSpaceRegion"]) ? "" : ConfigurationManager.AppSettings["RackSpaceRegion"];
                CloudFilesProvider cloudFilesProvider = getProvider();
             
             
                cloudFilesProvider.CreateObjectFromFile(container, imageFullPath, imageFileName, "image/jpeg", 4096, null, region, null, false);


             
            }
            catch (Exception ex)
            {
                WriteLog.GenerateMessageError(make, part, ex);
            }
            return imageFilePath;
        }


   private static CloudFilesProvider getProvider()
        {
            string rackUsername = string.IsNullOrEmpty(ConfigurationManager.AppSettings["RackSpaceUserName"]) ? "" : ConfigurationManager.AppSettings["RackSpaceUserName"];
            string rackApiKey = string.IsNullOrEmpty(ConfigurationManager.AppSettings["RackSpaceAPIKey"]) ? "" : ConfigurationManager.AppSettings["RackSpaceAPIKey"];


            CloudIdentity cloudIdentity =
                new CloudIdentity() { APIKey = rackApiKey, Username = rackUsername };
            return new CloudFilesProvider(cloudIdentity);
        }




Test Database connection on server


When you are on server and want to check connection then you can do with simple one file.

Below are the steps for that.

1) On desktop, create new text document file. it would be New Text Document.txt file.
2) Then change the extension of file name with .udl.
3) After then double click on file name it will open connection dialogue box as below.




















4) Enter your sql server credentials.
5) If all informations are right then dropdown of databse will filled by name of databases on server.



Friday, 9 October 2015

URL Rewrite Rules to redirect website to WWW and HTTPS in IIS

Here is rules to redirect website to website.com to www.website.com

Also if your website running in both http and https then you can write rules as per below.

 <rule name="Redirect http" patternSyntax="ECMAScript" stopProcessing="true">
          <match url=".*"></match>
          <conditions>
            <add input="{HTTP_HOST}" pattern="^website.com$"></add>
          </conditions>
          <action type="Redirect" url="http://www.website.com/{R:0}" redirectType="Permanent" appendQueryString="true"></action>
        </rule>
        <rule name="Redirect https" patternSyntax="ECMAScript" stopProcessing="true">
          <match url=".*"></match>
          <conditions>
            <add input="{HTTPS}" pattern="https://website.com$"></add>
          </conditions>
          <action type="Redirect" url="https://www.website.com/{R:0}" redirectType="Permanent" appendQueryString="true"></action>
        </rule>

Wednesday, 26 November 2014

Create CheckBoxList In Asp.net MVC


There is not any specific object like ChechboxList in MVC. yes you can install package and work with it
but you can do it without installing package.

Let's take one example.

you want to display days like below. you can take seven checkbox and to get value of it written seven times code to whether it is checked or not
in cotroller. instead of written seven times just create list object and create for loop and all values at controller side.



Model:

In model create static list
 public class CheckBoxItem
    {
        public string Name { get; set; }
        public string Value { get; set; }
        public string Label { get; set; }
        public bool Checked { get; set; }

    }



  public class EventModel
    {
        public EventModel()
        {
            WeekDays = DaysList();
        }

public List<CheckBoxItem> WeekDays { get; set; }

  public static List<CheckBoxItem> DaysList()
        {
            var list = new[]
            {
              new CheckBoxItem { Name = "Sunday", Value = "1", Label = "Sunday", Checked = false},
              new CheckBoxItem { Name = "Moday", Value = "2", Label = "Moday", Checked = false},
              new CheckBoxItem { Name = "Tuesday", Value = "3", Label = "TuesDay", Checked = false},
              new CheckBoxItem { Name = "Wednesday", Value = "3", Label = "Wednesday", Checked = false},
              new CheckBoxItem { Name = "Thursday", Value = "3", Label = "Thursday", Checked = false},
              new CheckBoxItem { Name = "Friday", Value = "3", Label = "Friday", Checked = false},
              new CheckBoxItem { Name = "Saturday", Value = "3", Label = "Saturday", Checked = false},

            };
            return list.ToList();
        }

}


View:

@for (int i = 0; i < EventTest.Models.EventModel.DaysList().Count(); i++)
         {
                 @Html.CheckBoxFor(m => m.WeekDays[i].Checked, new { id = @EventTest.Models.EventModel.DaysList()[i].Value })
                 @EventTest.Models.EventModel.DaysList()[i].Name
        }

Controller:
  public ActionResult CreateEvent(EventTest.Models.EventModels e)
        {
  for (int i = 0; i < e.RepeatType.WeekDays.Count; i++)
                    {
                        if (e.RepeatType.WeekDays[i].Checked)
                        {
                            ChkDayName += EventTest.Models.EventModel.DaysList()[i].Value + ",";
                        }
                    }
                        ChkDayName = ChkDayName.TrimEnd(',');
}

File upload using Model Binding in MVC

I have search through and all solutions are like that there is extra button to upload file
My requirement was to save file on final submit button. I am using model binding to insert data.


 Below is the code to upload file it is very simple and straight forward.

 Model:




















Controller:

     [HttpPost]
        public ActionResult CreateEvent(Models.EventModels e)
        {
            if (ModelState.IsValid)
            {
          int newEventId = eventService.InsertEvent(....);

           if (Request.Files.Count > 0)
                {
                    var file = Request.Files[0];
                    if (file != null && file.ContentLength > 0)
                    {
                        string savePath = SaveImage(file, newEventId);
                        eventService.UpdateEventLogo(newEventId, savePath);

                    }
                    }

In the saveImage function save your image in your folder.


View:

    Add enctype attribute in your form

    @using (Html.BeginForm("CreateEvent", "Event", FormMethod.Post, new { enctype = "multipart/form-data" }))

    Just add this
    @Html.TextBoxFor(m => m.BaseEvent.Logo, new { type = "file" })

    so after click on final submit button you will get Request.Files object.

Friday, 31 October 2014

Incremenent counter in nested for loop and maintain parent-child relationship(XSLT)


My requirement was to increment counter for each order and orderitems table. It is very simple in C# because
you can set the value of variable in each loop but in XSLT once you declare the variable you can not
change it. I have tried with couple of hours and at last found solution with scripting function in XSLT.

Below is my input XML

<orders>
<orderItems>
<Name>Test1</Name>
</orderitems>
<orderItems>
<Name>Test2</Name>
</orderitems>
<orderItems>
<Name>Test3</Name>
</orderitems>
</Orders>
<orders>
<orderItems>
<Name>Test4</Name>
</orderitems>
<orderItems>
<Name>Test5</Name></orderitems>
</Orders>

And here is my output XML.

I want to loop through all orders and orderitems and create seperate node and maintain parent- child
relationship.


<orderItems>
<Id>1 </Id>
<Name></Name>
<ParentID>0</ParentID>
</orderitems>
<orderItems>
<Id>2</Id>
<Name>Test1</Name>
<ParentID>1</ParentID>
</orderitems>
<orderItems>
<Id>3</Id>
<Name>Test2</Name>
<ParentID>1</ParentID>
</orderitems>
<orderItems>
<Id>4</Id>
<Name>Test3</Name>
<ParentID>1</ParentID>
</orderitems>

<orderItems>
<Id>5</Id>
<Name></Name>
<ParentID>0</ParentID>
</orderitems>
<orderItems>
<Id>6</Id>
<Name>Test4</Name>
<ParentID>5</ParentID>
</orderitems>
<orderItems>
<Id>7</Id>
<Name>Test5</Name>
<ParentID>5</ParentID>
</orderitems>

Here is my XSLT file

<xsl:for-each select="Orders">
     <xsl:variable name="var:v3" select="userCSharp:AddToCounter()" />
        <xsl:variable name="var:v5" select="userCSharp:GetCounter()" />


          <OrderItems>
      <Id><xsl:value-of select="userCSharp:GetCounter()"/></Id>
<Name>Test5</Name>
<ParentID>0</ParentID>
</orderitems>

    <xsl:for-each select="OrderItems">
            <xsl:variable name="var:v4" select="userCSharp:AddToCounter()" />
     <OrderItems>
      <Id><xsl:value-of select="userCSharp:GetCounter()"/></Id>
<Name>   <xsl:value-of select="$var:v5"/> </Name>
<ParentID>0</ParentID>
</orderitems>


    </xsl:for-each>
</xsl:for-each>

   
Add below script

 <msxsl:script language="C#" implements-prefix="userCSharp">
    <![CDATA[
    int mCounter= 1;
    public bool  AddToCounter()
    {
      mCounter = mCounter + 1;
      return true;
    }
 
    public int GetCounter()
    {
      return mCounter;
    }
   ]]>
  </msxsl:script>

Thursday, 14 August 2014

Generate Footer Content using ITextSharp


ITextSharp provides the Pdfpageeventhandler class to handle the event at the time to generate pdf file. If you want to handle the event on start of page
or when close the pdf then inherit your class with Pdfpageeventhandler.

If you want to display footer on every page then can do this in OnEndPage event.

Below are the sample code to display content in footer

   public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);

            PdfTemplate tmpFooter = pdfContent.CreateTemplate(600, 300);
             tmpFooter.MoveTo(1, 1);
            // Place the footer content
            tmpFooter.Stroke();
            // Begin writing the footer
            tmpFooter.BeginText();
          // Bold text for ther headers
            tmpFooter.SetFontAndSize(boldFont, 9);
            tmpFooter.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Total: ", 400, 80, 0);
            // Regular text for infomation fields
            tmpFooter.SetFontAndSize(baseFont, 9);
            tmpFooter.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "$" + Total, 500, 80, 0);

            int pageN = writer.PageNumber;
            String text =  pageN + " of " + TotalPages;
            float len = baseFont.GetWidthPoint(text, 8);
            Rectangle pageSize = document.PageSize;
            pdfContent = writer.DirectContent;
            tmpFooter.SetFontAndSize(boldFont, 8);
            tmpFooter.SetTextMatrix(pageSize.GetLeft(440), pageSize.GetBottom(10));
            tmpFooter.ShowText(text);

            // End text
            tmpFooter.EndText();
            // Stamp a line above the page footer
            pdfContent.SetLineWidth(0f);
            pdfContent.MoveTo(20, 100);
            pdfContent.LineTo(580, 100);
            pdfContent.Stroke();
            pdfContent.AddTemplate(tmpFooter, 30, 1);


        }