Showing posts with label Asp.net / C#. Show all posts
Showing posts with label Asp.net / C#. Show all posts

Monday, 2 December 2024

How to Create a Generic Method to Get the Enum Description in C#

        public static SelectList GetSelectListForEnumWithDescription(Type enumType)
        {
            var list = new List<Object>();
            Array enumValues = Enum.GetValues(enumType);
         
            foreach (Enum enumValue in enumValues)
            {
                list.Add(new
                              {
                                 ID = (int)Enum.Parse(enumType, enumValue.ToString()),
                                 Value = GetEnumDescription(enumValue)});
                               }
              return new SelectList(list, "ID", "Value");
        }

        public static string GetEnumDescription(Enum value)
        {

            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[]) fi.GetCustomAttributes(typeof (DescriptionAttribute), false);

            if (attributes != null && attributes.Length > 0)

                return attributes[0].Description;

            else return value.ToString();
        }
    }

Tuesday, 11 March 2014

MetadataException: Unable to load the specified metadata resource in Visual Studio 2012 or in Entity Frame work

When ever you are getting this error , just be sure that this property was bind in you Entity Framework.

Just open your  .edmx file , go to the properties and then set the property of the "Metadata Artifact Processing"  to "Embed in Output Assembly". That's all your problem is fixed.


Monday, 17 June 2013

Error 349: Duplicate headers received from server in Google Chrome while rendering PDF using ITextSharp in Asp.Net MVC



While working on generating  PDF in Asp.Net MVC3, I got a peculiar error while rendering the PDF in Chrome browsers, which is not being found in any other browsers like Internet Explorer or Fire Fox.
This error comes because chrome browsers doesn't ignore duplicate headers. This can be addressed easily the following ways, if you or your web app is sending out headers. Then check the following things:

 1. Enclose fileName using “”. i.e
Response.Addheader('Content-Disposition: attachment; filename="' + fileName '"');
instead of
Response.Addheader('Content-Disposition: attachment; filename='+ fileName);
2. If possible replace spaces and commas (,) with underscores (_)
 string regExp = @"[^\w\d]";
Response.AddHeader("content-disposition""attachment;filename=" + "Test_PDF_" + 
                           Regex.Replace(model.CompanyName, regExp, "_")+ "_" +
                              Regex.Replace(model.FullName, regExp, "_") + "_" +                                                         DateTime.Now.ToShortDateString());teString());

3. Explicitly tell Asp.Net MVC to override headers by setting optional replace parameter to true.
Response.AddHeader("Content-type: application/pdf",true);
Happy Coding!

Friday, 14 June 2013

How to prevent the multiple submit of record in ASP.Net MVC using JQuery

There are various methods are available to do that one, it can be done using JQuery, using sessions or Filters.


Method -1 ( Using JQuery Approach)
 $('form').submit(function () {
        if ($(this).find('.input-validation-error').length == 0) {
            $(this).find(':submit').attr('disabled''disabled');
        }
    });

This is the simplest method to prevent the multiple submission of the record in MVC and even it works on JQuery Unobstructive validations.

Happy Coding!

Tuesday, 23 April 2013

Blank out a form/ reset a form with jQuery


First method:
<form id="form">
<input type="text" value="Here is some data" id="data" />
<input type="button" value="Clear Input" id="button" />
</form>

$(function(){
 
    $('#button').click(function(){
       $(':input','#form').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked,selected');
    });
});

Second method:
function clearForms()
{
  var i;
  for (i = 0; (i < document.forms.length); i++) {
    document.forms[i].reset();
  }
}

Happy Coding!

Friday, 1 February 2013

Images are not updating in the IE on updating the Image file in websites using asp.net

This is a situation that occurs to each and every web developer who is developing the website.
Being a web developer using Microsoft .Net Framework i found this issue almost every next user it has. So, there are lot of solutions to this problem but I had found one of them is to be a very fine for the website  I am developing.


These are Some of the solutions that peoples nearby told me and some I find out in googling.

1) You need to remove the cache while updating the record, so the previous image is removed from the cache.

2)Force loading the web-page once image  is updated.

3) Load the image asynchronously only as per the current time.

However I like the last solution, i.e. is as below:

solution:
<img alt="Image" id="imgApp" src="@Url.Content("~/Images/Thumbnails/Apps/" + Model.App.ID + ".png?version=" + DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture))"

I had done this thing in mvc3 but you can do it any language.

Thursday, 31 January 2013

Generate Random Numbers of n length in C# / Asp.net

Sometimes it is required to generate  random numbers of length=n, so in that case the code below will help you to generate. Here by default it will generate random number of size 10 because i had used default value for the length=10 if no value are passed while calling it.


//Method to generate Random Numbers of n length
        public static string GenerateRandomNumbers(int length = 10)
        {
            //Initiate objects & vars 
            byte[ ] seed = Guid.NewGuid().ToByteArray();
            Random random = new Random(BitConverter.ToInt32(seed, 0));
            int randNumber = 0;
            //Loop ‘length’ times to generate a random number or character
            String randomNumber = "";
            for (int i = 0; i < length; i++)
            {
                randNumber = random.Next(48, 58);
               
randomNumber = randomNumber + (char)randNumber;
                //append random char or digit to
randomNumber string

            }
            return
randomNumber ;
        }


How to call the Method:
1)  string randomNumber= GenerateRandomNumbers( ); will generate a  random number of length=10.

2) string randomNumber= GenerateRandomNumbers(5); will generate a  random number of length=5.

 

A simplest way of Encrypting and Decrypting in C#.

Microsoft has provided a simplest way of encoding and decoding of strings  by using the System.Text.Here is the Code below to do Encryption and Decryption.


using System.Text;
For Encryption
 string encryptedString= Convert.ToBase64String(Encoding.Unicode.GetBytes("Text to Encrypt"));

For Decryption
 string decryptedString=Encoding.Unicode.GetString(Convert.FromBase64String("Text to Decrypt"));


How simple is it?

Note:This type of Encryption is not good for encrypting the passwords or credit card or Debit card information's or Online transactions as these are prone to decoding easily and can be hacked. so these are good for sending email in coding format through URL etc.

How to make a group of checkbox behave like a Radio button or toggle button using JQuery

 I got a message from my project manager that the client wants check-box like look rather than radio buttons for Roles(such as Admin, Site Manager) but it need to behave like the radio button. so to do it I had applied below the Jquery snippet to achieve it.

 $('input[name="Roles"]:checkbox').click(function () {
            var group = "input:checkbox[name='" + $(this).attr("name") + "']";
            $(group).attr("checked", false);
            $(this).attr("checked", true);
        });


Note:Here I am showing two check-boxes but you can keep n-numbers of and select only one like the radio button group.

Monday, 12 November 2012

Preventing the backbutton not to go to the previous URL when the control is in focus inside a textbox, textarea or radio button in any browser


While developing a website in Asp.net MVC4, I noticed that when my control is in focus inside a text-box or text-area, which are read only, it is moving to the parent of the current URL. In order to solve it i had written a JQuery below which will prevent the back to the parent URL in any browser and in any web developing programming languages.


    $(document).keydown(function(e) {
        var doPrevent;
        if (e.keyCode == 8) {
            var d = e.srcElement || e.target;
            if (d.tagName.toUpperCase() == 'INPUT' || d.tagName.toUpperCase() == 'TEXTAREA') {
                doPrevent = d.readOnly || d.disabled;
            }
            else
                doPrevent = true;
        }
        else
            doPrevent = false;

        if (doPrevent)
            e.preventDefault();
    });



Enjoy!..........

Monday, 5 November 2012

Issue with the sorting the telerik grid for Asp.net MVC

While working on telerik grid , I found a peculiar issue in Internet Explorer(IE) browsers. The issue is that on the column bound HeaderTemplate if you are providing a link for sorting purpose and if you used a label inside the link then the link will not work in IE but will work for all other browsers.


Solution: So, while providing the link text for sorting the grid on that column, just be care full that u must not used any label for that link. See below:

The code below will  not work:
column.Bound(m => m.Name).Template(
        @<text>
    <a target="_blank" href="@item.Url">@item.Name</a>
    </text>) .HeaderTemplate(
        @<text><a href="javascript:void(0)" class="t-link"> <label>Name<label> </a>  ---> This will not work
    </text>);



The code below will work:
 column.Bound(m => m.Name).Template(
        @<text>
    <a target="_blank" href="@item.Url">@item.Name</a>
    </text>) .HeaderTemplate(
        @<text><a href="javascript:void(0)" class="t-link"> Name </a>  ---> This will work.
    </text>);



Enjoy!.......

Friday, 2 November 2012

In MVC4 Telerik grid I got an error that telerik.textbox.js not found in the 'Script\telerik.textbox.js'

This is the tricky one, there is no problem in any where but it is throwing the problem because you might have passed some integer value to the column bound in the telerik grid in mvc3/mvc4.

There are two ways to fix it:

Method 1:

  Download the telerik.textbox.js and put in the specified location and it will work fine.

Note: Don't go for this method, since you are adding some more bytes to the  size of the Cod.

 Method 2:

 Just while binding the int value to the grid just convert it into a string. That's all, now your code will work fine



Enjoy!...

Friday, 26 October 2012

After getting the Ajax result from the Action Method the the view is not updating in mvc3/mvc4

One of my friend while doing a task of a project , he implemented the Ajax call to send request to the  action method. he had done it and resend the model to the client side, but the data is not updating in the view.

So, I thought of a while and scrutinized it and found that the model is updated when the data comes from the action method but it is not updating the view. so, here is the trick how to do it.

$.ajax({
                data: { retailLocation: $("#ddlLanguages").val().split('-')[1] + "-" + this.value },
                url: '/App/index',
                success: function (result) {
                    $("#container").empty().html(result);
                    $('#container').fadeIn('fast');


                },
                complete: function (result) {
                    $("#RetailPartnerLocation option:contains(" + currentselection + ")").attr('selected', 'selected');
                },
                Error: function (result) { alter("Error occured while processing"); }
            });


Here you need to empty the container where the previous data exist and bind the new data to it.

How to Show the date like facebooks shows when you provide comments such as 1 min ago, 2 days ago, 1 Month Ago in Asp.Net/ Asp.Net MVC 2/MVC 3/ MVC 4

While working on a project , I need to show the comments published or updated as 1 min ago, 1 Hours ago, so on. So in order to do it I had written a helper class to do it for me.

Here is the code below:
 public static string GetFormattedDate(string date)
        {
            string formattedDate = string.Empty;
            TimeSpan ts = System.DateTime.Now - DateTime.Parse(date);
            int weeks = (int)(DateTime.Now - DateTime.Parse(date)).TotalDays / 7;

            if (ts.Minutes == 0)
                formattedDate = "Few Seconds Ago";
            if (ts.Minutes > 0 && ts.Minutes < 59)
                formattedDate = ts.Minutes + (ts.Minutes == 1 ? " Minute Ago" : " Minutes Ago");
            if (ts.Hours > 0 && ts.Hours < 24)
                formattedDate = ts.Hours + (ts.Hours == 1 ? " Hour ago" : " Hours ago");
            if (ts.Days >= 1 && ts.Days<30)
            {
                if (ts.Days == 1)
                {
                    formattedDate = "Today";
                }
                else if (ts.Days>1 && ts.Days < 7)
                {
                    formattedDate = ts.Days + (ts.Days == 1 ? " Day ago" : " Days ago");
                }
                else
                {
                    formattedDate = (ts.Days / 7).ToString() + ((ts.Days / 7).ToString() == "1" ? " Week Ago" : " Weeks Ago");
                }
            }
            else if (ts.Days >= 30 && ts.Days<365)
            {
                formattedDate = ts.Days/30 + ( ts.Days<60 ? " Month ago" : " Months ago");
            }
            else if(ts.Days>=365)
            {
                formattedDate = ts.Days / 365 + ( ts.Days < 730 ? " Year ago" : " Years ago");
            }
          
            return formattedDate;
        }

How to Write a Extension method to strip html-tags from a rich text Editor in ASP.Net/ MVC

Today while working with CKEditor , I find out that what ever I provide in the Editor body and saved, it is not properly translating the html tags such as paragraph in the Editor body.

So to fix it I had written an extension method to strip the HTML tags as :


        public static string StripHtml(string inputString)
        {
            if (!string.IsNullOrEmpty(inputString))
                return Regex.Replace(inputString, "<.*?>", string.Empty);

            return string.Empty;

        }


How to call: Classname.StripHtml("some string");

Friday, 20 July 2012

How to Show a Pop-Up Message Window in Asp.net (Like the Message Window in Windows Forms)

You all might aware of that in win forms you might have used Message.Show("Some Text")  to show some information. However in Asp.net forms you might have used Alert( ) or used a Literal or Label to Show some Message when you want to show some thing to the user like  1)  Your Resume has been updated Successfully. or 2) User Created Successfully or 3) A mail has been sent to your Mail ID and so on. In above all case the best one is to be go for a Literal or a Label and show the message there. How ever you want to show a message like alert using Literal, then go for the code below:


public static void ShowMessage(Page page,string message)
{
     Literal literalMessage=new Literal( );
     literalMessage.Text="<script>alert('" + message + " ')</script>";
     page.Controls.Add(literalMessage);
}

How we can use the above code :-

Just think that we want some message on a button click event,then we can use it as:

protected void btnSave_Click(Object sender, EventArgs e)
{
    ShowMessage(this, "Data updated Successfully!");
}

Enjoy it...........


Thursday, 24 May 2012

IEnumerable.Count() is a bad style of Coding, Why?

IEnumerable<Participant> participants=GetParticipants();

if(products.count()==0)
{
       SomeControls.Visible=false;
}
else
{
     SomeControls.Visible=true;
}
The wrong thing with the above code is that Count() is a Linq extension Method that literally iterates through every item in an  enumerable( here it is participants). In other words it won't short circuit after it finds more than zero items and will continue iterating through every single item. And while, that one may be fast operation in Dev environment but it will be a slow process in production. This is because of Linq's deferred Execution.

How we can refine the above Code

The above Code can be refined by changing it into as:
IEnumerable<Participant> participants=GetParticipants();

if(products.Any())
{
       SomeControls.Visible=false;
}
else
{
     SomeControls.Visible=true;
}

In the above code once the expression finds more than one item, it simply stops iterating and just increasing the Optimization time.

Happy Coding.........!

Wednesday, 9 May 2012

Writing log files for Applications in C# with time stamp

 A sample code which creates a log file (one per day & instance) 
and puts in time-stamped log entries into it. The file names are such 
that sorting them in Windows File Explorer is very easy for the SysAdmin
 
 
using System.IO;
public void WriteLogLine(string sCallerName, string sLogFolder, 
                        long lCallerInstance, string sLogLine)
{
  lock(this)
  {
    string sFileName;
    sFileName = String.Format("{0}_{1:yyyy.MM.dd}_{2:00}.log", 
                  sCallerName, DateTime.Now, lCallerInstance);
    StreamWriter swServerLog = 
           new StreamWriter(sLogFolder + sFileName, true);
    swServerLog.WriteLine(
           String.Format("[{0:T}] {1}", DateTime.Now, sLogLine));
    swServerLog.Close();
  }
}

Title: Get the description of a Enum value.

Some times it is required to get the Enum description to be used inside your drop down control 
or list box control or some where else, here is a small program that will help you to do this.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Text;

namespace LinkedIn.Utility
{
  /// <summary>
  /// A helper class for enums.
  /// </summary>
  public static class EnumHelper
  {
    /// <typeparam name="TValue">usually int</typeparam>
    public static List<TValue> GetValues<TEnum, TValue>()
    {
      List<TValue> values = new List<TValue>();
      Array array = Enum.GetValues(typeof(TEnum));
      foreach (TValue item in array)
      {
        values.Add(item);
      }

      return values;
    }

    /// <summary>
    /// Get the description of a <see cref="Enum" /> value.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <returns>A description of the <see cref="Enum" /> value.</returns>
    public static string GetDescription(Enum value)
    {
      FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
      DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fieldInfo.GetCustomAttributes(
            typeof(DescriptionAttribute), false);

      return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
    }

    /// <summary>
    /// </summary>
    /// <typeparam name="TEnum"></typeparam>
    /// <param name="enumeratedType"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool HasFlag<TEnum>(this TEnum enumeratedType, TEnum value)
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
      if ((enumeratedType is Enum) == false)
      {
        throw new InvalidOperationException("Struct is not an Enum.");
      }

      if (typeof(TEnum).GetCustomAttributes(
          typeof(FlagsAttribute), false).Length == 0)
      {
        throw new InvalidOperationException("Enum must use [Flags].");
      }

      long enumValue = enumeratedType.ToInt64(CultureInfo.InvariantCulture);
      long flagValue = value.ToInt64(CultureInfo.InvariantCulture);

      if ((enumValue & flagValue) == flagValue)
      {
        return true;
      }

      return false;
    }
  }
}

Enjoy............!
   

Tuesday, 24 April 2012

How to change the Image of a button or control on MouseOver as in Windows7


<script type="text/javascript">
        function OnMouseOver( ) {           
            document.getElementById("imgbtnSubmit").src = "btnActive.png";
        }
        function OnMouseOut( ) {
            document.getElementById("imgbtnSubmit").src = "btnInActive.png";
        }
    </script>

Method 1 :-
    Call the above JavaScript function on client MouseOver and MouseOut;

Method 2 :-
    Using styles in the CSS file,
 You can change the image on hover and on out of focus you can show the default Image.

for e.g. :
              <asp:ImageButton   ID="imgBtnSubmit"  ImageUrl="~/Image/btnInActive.png" CssClass="btnSubmit" runat="server"></asp:ImageButton>

In the CSS File:
      .btnSubmit:hover {backgroundImage:url("~/images/btnActive.png"); }

 Method 3 :-

In the page's Load event, call the Add method of the control's Attributes collection.

imgbtnSubmit.Attributes.Add("onmouseover","OnMouseOver( )");
imgbtnSubmit.Attributes.Add("onmouseout", "OnMouseOut( )");

Just enjoy..........that's all.