Monday, December 31, 2012

Happy New Year 2013

May The Every Moment Of Coming New Year Brings Happiness And Prosperity In Life, Enjoy The Every Moment Of Life. Happy New Year.

new year scraps
NextGenTech Software Solutions

Monday, September 3, 2012

How to Loading and Saving JSON data?

Here is a very good article for this
http://knockoutjs.com/documentation/json-data.html

Sunday, August 26, 2012

How to get Country list without using Database in C#?

 Do you know we can get Country List without using Database! Here i am showing how to get Country list by simply using the CultureInfo class .

This function ca be use for returning Country List by an region like here i used "de-DE" for Germany. for that you have to bake this function parametrized function by passing a string as regional code

/// Function Name: FillCountries
        /// Bishnu Tewary
        /// 01-02-2012
        /// <summary>
        /// This methode will set _countryList with country name in Germany
        /// </summary>
        private void FillCountries( )
        {
            this._countryList = new List<Country>();
            try
            {
                foreach (CultureInfo objCultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
                {
                    ////de-DE is for German and NativeName will return countryname in Germany
                    RegionInfo objRegionInfo = new RegionInfo("de-DE");
                    Country objCountry = new Country { CountryName = objRegionInfo.NativeName, CountryCode = objRegionInfo.TwoLetterISORegionName };
                    if (!this._countryList.Contains(objCountry))
                    {
                        this._countryList.Add(objCountry);
                    }
                }
            ////Sort this._countryList in ascending order
                this._countryList = (from c in this._countryList orderby c.CountryName ascending select c).ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Thursday, May 24, 2012

How to use gradient with background color?

 Here is how to use gradient with background color in css .
.HeaderWrapper {  
float:left; display:inline;
width:100%;
background:#5EB440 ;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#236F44', endColorstr='#5EB440'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#236F44), to(#5EB440)); /* for webkit browsers */
background: -moz-linear-gradient(top,  #236F44,  #5EB440); /* for firefox 3.6+ */
}

How to make a rounded corner div?

Here is the style for making a rounded corner div

.round-corner-box {
margin:0px; padding:0px;
border:1px #5EB440 solid;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
 border-radius: 10px;
}

But don't know this is not working in IE for me....
any suggestions! 

Tuesday, April 10, 2012

How to get the primarykey name of the table in EntityFramework C#?

 Here is how to get the primary key of an entitySetName
var primaryKeyName = objDb
   .MetadataWorkspace
   .GetEntityContainer(objDb.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace)
   .BaseEntitySets
   .First(meta => meta.ElementType.Name == entitySetName)
   .ElementType
   .KeyMembers
   .Select(k => k.Name)
   .FirstOrDefault();

How to check the Key exists or not in EntityFramework C#?

This method will help to get the key exists or not from an entityset in EntityFramework
Here
TargetTable is the Enum where I have all the tables names
string keyValue is the value for which i am checking exists or not

 public bool CheckKey(TargetTable tableName, string keyValue, MyMotorEntities objDb)
{
bool isKeyAlreadyExists = false;
try
                            {
                                string entitySetName = Enum.GetName(typeof(TargetTable), tableName);
                                var primaryKeyName = objDb
   .MetadataWorkspace
   .GetEntityContainer(objDb.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace)
   .BaseEntitySets
   .First(meta => meta.ElementType.Name == entitySetName)
   .ElementType
   .KeyMembers
   .Select(k => k.Name)
   .FirstOrDefault();
                                List<KeyValuePair<string, object>> lstEnum = new List<KeyValuePair<string, object>>();
                                lstEnum.Add(new KeyValuePair<string, object>(primaryKeyName, keyValue));
                                var lsttype = from t in lstEnum select t;
                                IEnumerable<KeyValuePair<string, object>> IeList = ((IEnumerable<KeyValuePair<string, object>>)lsttype).Select(x => x).AsQueryable();
                                System.Data.EntityKey key = new System.Data.EntityKey("MyMotorEntities." + entitySetName , IeList);
                                var tbl = objDb.GetObjectByKey(key);
if (tbl!=null)
                {
                    isKeyAlreadyExists = true;
                }
                            }
                            catch (Exception ex)
                            {

                            }
 return isKeyAlreadyExists;
}

Tuesday, March 20, 2012

How to get Value from an Enum Item in asp.net?

Here i am showing how to get value from an Enum Item

/// <summary>
        /// GetDescriptionFromEnumValue is returns the name or value for an Enum Item
        /// </summary>
        /// <param name="value">Enum Value</param>
        /// <returns>Description For Enum</returns>
        public static int GetValueFromEnum(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            int val = (int)fi.GetValue(value);

            return val;
        }
Use this method
-----------------
 objtblLog.LogType = EnumUtility.GetValueFromEnum((Logtype)Session.ErrorLogtype);

Where Session.ErrorLogtype is an integer value

Thanks to my Project manager , who guide me lot to know these things and how to handle a project to get better performance ... "Thank you Sir"

How to get the Key from an Enum in asp.net?

This method will return the Key or Description from an Enum Item

 /// <summary>
        /// GetDescriptionFromEnumValue is returns the name  for an Enum Item
        /// </summary>
        /// <param name="value">Enum Value</param>
        /// <returns>Description For Enum</returns>
        public static string GetDescriptionFromEnumItem(Enum value)
        {
            DescriptionAttribute attribute = value.GetType()
                .GetField(value.ToString())
                .GetCustomAttributes(typeof(DescriptionAttribute), false)
                .SingleOrDefault() as DescriptionAttribute;
            return attribute == null ? value.ToString() : attribute.Description;
        }

Here how to use this function from other class
-----------------------------------------------
 /// Function Name: GetComTypes
        /// Bishnu Tewary
        /// 05-03-2012
        /// <summary>
        /// GetTitleNameByValue function return the Name of an enum item for its value
        /// </summary>
        /// <param name="value"> value of the enumitem</param>
        /// <returns>name of the value</returns>
        public string GetTitleNameByValue(int value)
        {
            TitleTypes enumItem = (TitleTypes)Enum.Parse(typeof(TitleTypes), Convert.ToString(value));
            return EnumUtility.GetDescriptionFromEnumItem(enumItem);
        }

How to use Description with an Enum Key in asp.net?

What happened if we have to bind a dropdownlist from Enum which holds Titles like Mr and Mrs but we have to show the textvaluefield like "Mr." and "Mrs."? Ok for this type of requirement we can use description attribute with the Key of a particular Enum, Here I am showing how to do that.

/// <summary>
        /// Enumeration TitleTypes use for getting the Titles
        /// Here I use DescriptionAttribute for holding the "Mr." Because "." is not supported in variable declaration
        /// </summary>
        public enum TitleTypes
        {
            /// <summary>
            /// Title As Mr and DescriptionAttribute set to Mr.
            /// </summary>
            [DescriptionAttribute("Mr.")]
            Mr = 1,

            /// <summary>
            /// Title As Mrs and DescriptionAttribute set to Mrs.
            /// </summary>
            [DescriptionAttribute("Mrs.")]
            Mrs = 2
        }

Cheers!

How to bind a dropdownlist from Enum in MVC3?

This post will help you to bind a dropdownlist from an Enum in MVC 3 application. Here i create a methode which will return an IQueryable<SelectListItem> list from a given enum.
the methode is like bellow
public static IQueryable<SelectListItem> BindDropdownListFromEnum<T>()
        {
            List<SelectListItem> lstEnum = new List<SelectListItem>();
            var lsttype = from t in lstEnum select t;
            try
            {
                T objType = Activator.CreateInstance<T>();
                foreach (T enumValue in Enum.GetValues(typeof(T)))
                {
                    FieldInfo fi = typeof(T).GetField(enumValue.ToString());
                    DescriptionAttribute da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
                    SelectListItem lstItem = new SelectListItem();
                    int val = (int)fi.GetValue(enumValue);
                    if (da != null)
                    {
                        lstItem = new SelectListItem { Text = da.Description, Value = Convert.ToString(val) };
                    }
                    else
                    {
                        lstItem = new SelectListItem { Text = fi.Name, Value = Convert.ToString(val) };
                    }

                    if (!lstEnum.Contains(lstItem))
                    {
                        lstEnum.Add(lstItem);
                    }
                }

                lsttype = from t in lstEnum select t;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return ((IEnumerable<SelectListItem>)lsttype).Select(x => x).AsQueryable();
        }

Here if the enum has description for its Key then it will return the Key as Description and the Value will be the enum value. as a list of IEnumerable<SelectListItem> where SelectListItem's key and value will be the enum types key and value respectively.

In controller
-----------------
 IEnumerable<SelectListItem> lstUsertypes = EnumUtility.BindDropdownListFromEnum<UserType>();
 ViewBag.UserType = lstUsertypes;

In view
----------
Usertype :  @Html.DropDownList("UserType", "-- Select All --")

Enum
-----------
 /// <summary>
    /// Enumeration UserType use for Get User Type
    /// </summary>
    public enum UserType
    {
        /// <summary>
        /// For Private Value is 1
        /// </summary>
        Private = 1,

        /// <summary>
        /// For Company Value is 2
        /// </summary>
        Company = 2,

        /// <summary>
        /// For Organisation Value is 3
        /// </summary>
        Organisation = 3
    }

How to get client IP Address in MVC3?

Before implementing this I did so many things but not succeed like this to get the client Ip address means from where the browser open. In one of my project i have to save the client IP address, browser name  and browser version. Its a MVC 3 razor application.
  So here i am showing you how to get these

        public static string GetIPAddress(HttpRequestBase request)
        {
            string ip = string.Empty;
            try
            {
                ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (!string.IsNullOrEmpty(ip))
                {
                    if (ip.IndexOf(",") > 0)
                    {
                        string[] allIps = ip.Split(',');
                        int le = allIps.Length - 1;
                        ip = allIps[le];
                    }
                }
                else
                {
                    ip = request.UserHostAddress;
                }      
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return ip;
        }

         public static string GetBrowserType(HttpRequestBase request)
        {
            try
            {
                HttpContext.Current.Session["BrowserType"] = request.Browser.Browser;
              
                return HttpContext.Current.Session["BrowserType"].ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

         public static string GetBrowserVesrsion(HttpRequestBase request)
        {
            try
            {
                HttpContext.Current.Session["BrowserVesrsion"] = request.Browser.MajorVersion;

                return HttpContext.Current.Session["BrowserVesrsion"].ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Thursday, February 2, 2012

How to update a record through EntityFramework in C#?

To update record with the help of EF we use this code
public void Update(tblAdmin objtblAdmin)
{
try
{
using (MyMotorEntities objDb = new MyMotorEntities())

{
var objAdmin = (from t in objDb.tblAdmins.Where(p => p.IdAdmins == objtblAdmin.IdAdmins) select t).FirstOrDefault();
if (objAdmin.IdAdmins > 0)
{objAdmin.Email = objtblAdmin.Email;
objAdmin.Firstname = objtblAdmin.Firstname;
objDb.SaveChanges();

}

}

ReportSuccess();

}
catch (Exception ex)
{
ReportError(ex);
}
}

But what happens when the tblAdmin has lots of fields :) ok don't worry we can use Attach for this.Attach allows us to attach to a record within the context, perform a straight replace on the record with the new modified record and save back the changes and All just within just 3 lines of codes... lolz :)

Here is this ...

public void Update(tblAdmin objtblAdmin)

{
try
{

using (MyMotorEntities objDb = new MyMotorEntities())
{
objDb.tblAdmins.Attach(objDb.tblAdmins.Single(c => c.IdAdmins == objtblAdmin.IdAdmins));
objDb.tblAdmins.ApplyCurrentValues(objtblAdmin);
objDb.SaveChanges();
}

ReportSuccess();
}
catch (Exception ex)
{
ReportError(ex);
}
}

Cheers :)

Wednesday, January 18, 2012

How to Paging Datalist or Repeater in asp.net C#?

 Here I am showing a simple but not like so :) i.e paging of a Repeater or datalist in asp.net using C#

.aspx Content
------------------
<asp:Repeater ID="rptPosts" runat="server" OnItemDataBound="rptPosts_ItemDataBound"
                            OnItemCommand="rptPosts_ItemCommand">
                            <ItemTemplate>
                          <asp:Label ID="lblSubject" runat="server" Text='<%#Eval("Subject")%>'></asp:Label>       
                            </ItemTemplate>
 </asp:Repeater>

<asp:Repeater ID="rptPages" runat="server">
                            <HeaderTemplate>
                                <table cellpadding="0" cellspacing="0" border="0">
                                    <tr>
                                        <td>
                                            <b>Page:</b>&nbsp;
                                        </td>
                                        <td>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <asp:LinkButton ID="btnPage" CommandName="Page" CommandArgument="<%#
                         Container.DataItem %>" CssClass="f-anchor" runat="server"><%# Container.DataItem %>
                                </asp:LinkButton>&nbsp;
                            </ItemTemplate>
                            <FooterTemplate>
                                </td> </tr> </table>
                            </FooterTemplate>
                        </asp:Repeater>
.cs Content
----------------
private void LoadData(int topicId)
        {
            lnkDelTopic.CommandArgument = Convert.ToString(topicId);
            lnkEditTopic.CommandArgument = Convert.ToString(topicId);
            PagedDataSource pgitems = new PagedDataSource();
            pl_post objPost = new pl_post();
            objPost.TopicId = topicId;
            postList = bl_forum.GetPostListByTopicId(objPost);
            pgitems.DataSource = postList;
            pgitems.AllowPaging = true;
            pgitems.PageSize = 5;
            pgitems.CurrentPageIndex = PageNumber;

            if (pgitems.PageCount > 1)
            {
                rptPages.Visible = true;
                ArrayList pages = new ArrayList();
                for (int i = 0; i < pgitems.PageCount; i++)
                    pages.Add((i + 1).ToString());
                rptPages.DataSource = pages;
                rptPages.DataBind();

            }
            else
                rptPages.Visible = false;

            rptPosts.DataSource = pgitems;
            rptPosts.DataBind();
        }

        protected void rptPosts_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label lblSubject = e.Item.FindControl("lblSubject") as Label;
            if (lblSubject.Text == string.Empty)
            {
                lblSubject.Text = "Re: " + Convert.ToString(Session["TopicName"]);
            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            rptPages.ItemCommand +=
               new RepeaterCommandEventHandler(rptPages_ItemCommand);
        }
        void rptPages_ItemCommand(object source,
                               RepeaterCommandEventArgs e)
        {
            PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
            //fillPageData();
            //fillReply();
            LoadData(Convert.ToInt32(Request.QueryString["TopicId"]));
        }
        public int PageNumber
        {
            get
            {
                if (ViewState["PageNumber"] != null)
                    return Convert.ToInt32(ViewState["PageNumber"]);
                else
                    return 0;
            }
            set
            {
                ViewState["PageNumber"] = value;
            }
        }

Will describe latter when i get some time but hope this helps you all