Skip to main content

Posts

Showing posts from 2013

Javascript : How to insert text into textbox or textare or input elements at teh cursor position

function insertAtCursor(myField, myValue) { // For IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } // For MOZILLA and others else if (myField.selectionStart || myField.selectionStart == '0' ) { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length; } else { myField.value += myValue; } }

How to convert Dictionary to a comma separated csv string in c#?

the following function will take the list of dictionary items to a comma separated csv string. public string ConvertToCSV(List<Dictionary<string, string>> items) {     if (!items.Any()) return string.Empty;     StringBuilder writer = new StringBuilder();     // Generating Header.     List<string> headers = items[0].Keys.Select(x => x).OrderBy(x => x).ToList();     writer.AppendLine(string.Join(", ", headers.Select(h => h)));     // Generating content.     foreach (var item in items)     writer.AppendLine(string.Join(", ", headers.Select(h => item[h])));     return writer.ToString(); }  

MVC : How to add attribute, class, readonly, custom attribute to @Html helper classes in MVC like @Html.TextBoxFor

Here I am using the examples for @Html.TextBoxFor class. 1) Adding attributes @Html.TextBoxFor(model=>model.FirstName,new{ Width="200px" }) 2) Adding Custom attribute @Html.TextBoxFor(model=>model.FirstName,new{ @data_type="number" }) Note : data_type will be converted to data-type by Razor engine. 3) Readonly & Class @Html.TextBoxFor(model=>model.FirstName,new{ @readonly="readonly", @class="firstname" })

MVC: How to use enum type in drop down list using mvc

To use enum type in dropdown list follow the following format. @Html.DropDownListFor(model => model.EnumName, new SelectList(Enum.GetValues(typeof(Namespace.EnumName))))    //Enum namespace MyNameSpace.Util {    public enum Days    {      Sunday,      Monday,      Tuesday,      Wednesday,      Thursday,      Friday,      Saturday    } } //Model public EnumTestModel {    MyNameSpace.Util.Days SelectedDay {get;set;} } Razor syntax for displaying Days in DropDownList is // View @Html.DropDownListFor(model => model.SelectedDay , new SelectList(Enum.GetValues(typeof(MyNameSpace.Util. Days ))))    

CSS: how to make iframe height adjust to content?

<style> .previewFrame {       cursor: hand;       width: 1360 px;       border: 8px solid #ccc;       height: 768px;       filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.5,M22=0.5,SizingMethod='auto expand');       -moz-transform: scale(0.5, 0.5);       -webkit-transform: scale(0.5, 0.5);       -o-transform: scale(0.5, 0.5);       -ms-transform: scale(0.5, 0.5);       transform: scale(0.5, 0.5);       -moz-transform-origin: top left;       -webkit-transform-origin: top left;       -o-transform-origin: top left;       -ms-transform-origin: top left;       transform-origin: top left; } </style> <iframe scrolling="no" frameborder="0" src="your-url" class="previewFrame"></iframe>

WCF Service in IIS7 - The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to ‘C:\WINDOWS\Microsoft.NET\Framework\v4.0.3019\Temporary ASP.NET Files’.

The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to ‘C:\WINDOWS\Microsoft.NET\Framework\v4.0.3019\Temporary ASP.NET Files’. To solve this issue just run the following command  in command line C:\Windows\Microsoft.NET\Framework\v4.0.30319> aspnet_regiis -ga “NT Authority\Network Service”

How to detect Scroll down and scroll up event using jQuery?

Use the following script to detect scroll up and scroll down events <script type="text/javascript"> $(document).ready(function(){ var LastScroll=0;   //  I am using div element's scroll here.     $("div").scroll(function(){          if(LastScroll<$("div").scrollTop())          {               //scroll down event           }           else            {                 //scroll up event             }              LastScroll=$("div").scrollTop();      }); }) </script>

Mapping .NET Data Types to MySQL Data Types

Mapping .NET Data Types to MySQL Data Types .NET Data Types MySQL Data Types System.Boolean boolean, bit(1) System.Byte tinyint unsigned System.Byte[] binary, varbinary, blob, longblob System.DateTime datetime System.Decimal decimal System.Double double System.Guid char(36) System.Int16 smallint System.Int32 int System.Int64 bigint System.SByte tinyint System.Single float System.String char, varchar, text, longtext System.TimeSpan time DateTimeOffset type is not supported.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Solution : start-> Run--> c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -iru use of -iru option -ir Installs and registers ASP.NET 4. This option is the same as the -i option except that this option does not change the CLR version that is associated with any existing application pools.   -  iru                    If ASP.NET is not currently registered with IIS, performs the tasks described for -i . If a previous version of ASP.NET is already registered with IIS, this option performs the tasks described for -ir .

MS SQL Server 2008 - Stored Procedure for Getting X meter radious of spacial data from a point

Stored Procedure to find data for x meter radious from a point using SQL Server geography data. Create Procedure GetXMeterRadiousData (  @RadiousInMeter INT=0,  @Point GEOGRAPHY=NULL,  @Mode VARCHAR(10)='DISTANCE' ) AS BEGIN DECLARE @g geography IF (@Mode='DISTANCE')   -- Using Distance method      BEGIN  -- Get the point             SELECT @g = geo FROM SpacialDataTable             WHERE geo = @Point             -- Get the results, radius @RadiousInMeter            SELECT * FROM SpacialDataTable            WHERE @g.STDistance(geo) <= @RadiousInMeter          END ELSE   -- Using INTERSECTS method       BEGIN  -- Get the center buffer, @RadiousInMeter radius  SELECT @g = geo.STBuffer(@RadiousInMeter) FROM SpacialDataTable  WHERE geo = @Point  -- Get the results within the buffer  SELECT * FROM SpacialDataTable WHERE @g.STIntersects(geo) = 1       END END

Facebook - How to invite a user to your facebook application?

Use the following method to invite a user to your facebook application. public bool InviteAFacebookUser(string AccessToken, string AppId, string Msg) {      bool result=false;      try      {            FacebookClient fbClient = new FacebookClient(AccessToken);            var args = new Dictionary<string, object>();            args["appId"] = AppId; //event id            args["message"] = Msg;            dynamic id = fbClient.Post("/me/apprequests", args);            result=true;        }        catch        {            //I am suppressing the exception.        }        return result; }

Facebook - How to post topic in facebook using FacebookClient

Facebook - Use the following method to feed a post on facebook using FacebookClient api in C# public bool PostOnWall(IDictionary<string, object> Parameters,string AccessToken) {     if (Parameters.Keys.Count > 0)     try     {          FacebookClient fbClient = new FacebookClient(AccessToken);          fbClient.Post("/me/feed", Parameters);          return true;     }     catch { }     return false; }

Facebook - How to get access permission from facebook for a user?

Use the following method to get access permissions of a user for a facebook Application using FacebookClient api. public IDictionary<string, object> GetPermissions(string AccessToken) {      IDictionary<string, object> me = new Dictionary<string, object>();      try      {                 FacebookClient fbClient = new FacebookClient(AccessToken);                 me = fbClient.Get("me") as IDictionary<string, object>;       }       catch { //suppressing all exception }       return me; }

C# - How to get Property Name and Value of a dynamic object?

C# - Dynamic Object Use the following code to get Name and Value of a dynamic object's property. dynamic d = new { Property1= "Value1", Property2= "Value2"}; var properties = d.GetType().GetProperties(); foreach (var property in properties) {     var PropertyName= property.Name; //You get "Property1" as a result     var PropetyValue= d.GetType().GetProperty(property.Name).GetValue(d, null); //You get "Value1" as a result // you can use the PropertyName and Value here  }

How to get ip address in c#

// Use the following code to get the user ipaddress public string GetCurrentIpAddress(HttpContextBase httpContext) { if (httpContext != null && httpContext.Request != null && httpContext.Request.UserHostAddress != null) return httpContext.Request.UserHostAddress; else return string.Empty; } //syntax for calling the above method. string UserIp = GetCurrentIpAddress(Request.RequestContext.HttpContext);

C# - Setting Last Session Id for a new request in asp.net

The following method used to set last session id to the new request. we can use the following mehtod to maintain the same session for a user with cross browser request or request from different locations ( different IP).     public void SetLastSession(string LastSessionId) {    HttpCookie cookie =      new HttpCookie ( "ASP.NET_SessionId" , LastSessionId) { Path = "/" ,   HttpOnly = true };    this .Context.Response.Cookies.Remove( "ASP.NET_SessionId" );    this .Context.Response.Cookies.Add(cookie); }

c# - object to string and string to object

The following methods is used to convert an object to string and string to object using c#. // Requires following Namespaces. using   System.IO; using System.Runtime.Serialization.Formatters.Binary; //Convert Object to String public string ObjectToString( object obj) {     MemoryStream ms = new MemoryStream ();           new BinaryFormatter ().Serialize(ms, obj);     return Convert .ToBase64String(ms.ToArray()); } //Convet String to Object public object StringToObject( string base64String) {     byte [] bytes = Convert .FromBase64String(base64String);     MemoryStream ms = new MemoryStream (bytes, 0, bytes.Length);     ms.Write(bytes, 0, bytes.Length);     ms.Position = 0;     return new BinaryFormatter ().Deserialize(ms); }