Translate

Home > 2014

2014

Entity Framework Connection Use As SqlConnection

Thursday, November 13, 2014 Category : , 0

        public static string GetConnectionString()
        {
            string entityConnectionString = ConfigurationManager.ConnectionStrings["ERPEntities"].ConnectionString;
            string providerConnectionString = new EntityConnectionStringBuilder(entityConnectionString).ProviderConnectionString;
            return providerConnectionString;
        }

C# DataTable to List Convert

Wednesday, November 12, 2014 Category : , 0


public static List DataTableToList(this DataTable table) where T : class, new()

        {
           try
            {
                List list = new List();
                foreach (var row in table.AsEnumerable())
               {
                    T obj = new T();
                    foreach (var prop in obj.GetType().GetProperties())
                    {
                        try
                        {
                            PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);

                            propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);

                        }
                        catch
                        {
                            continue;
                        }
                    }
                    list.Add(obj);
                }
                return list;
            }
            catch
            {
                return null;
            }
        }

ASP.net dropdown with searching textbox

Tuesday, September 30, 2014 Category : 0

    <link href="~/js/chosen.css" rel="stylesheet" type="text/css" runat="server" />
    <script src="<%#ResolveUrl("~") %>js/chosen.jquery.js" type="text/javascript"></script>



<asp:DropDownList ID="ddlAssignGroup" class="form-control"
     CssClass="chosen-select" Width="157px" runat="server">
</asp:DropDownList>


  <script type="text/javascript">

        var config = {
            '.chosen-select': {},
        }
        for (var selector in config) {
            $(selector).chosen(config[selector]);
        }
      </script>


Out put







at this point. everything is ok. but when this page is postback then this option is gone.
then i have find a solution by using this javascript code.

    <script type="text/javascript">
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_endRequest(function (s, e) {
            var config = {
                '.chosen-select': {},
            }
            for (var selector in config) {
                $(selector).chosen(config[selector]);
            }
        });
    </script>


this code actually fire when a post back occurs.

Jquery and css link
https://docs.google.com/file/d/0B2qzKDIYFsGgWFZHMFRDNU50SDg/edit

Silver light Comon Operation Syntext

Thursday, September 4, 2014 Category : 0

Datagrid  Date column format : 
<sdk:DataGridTextColumn Header="From" IsReadOnly="True"
                                                Binding="{Binding FromDate, StringFormat='{}{0:MM/dd/yyyy}'}" Width="auto"/>


<sdk:DataGridTextColumn Header="Discharge Date"
                                                Binding="{Binding DischargeDate, StringFormat='{}{0:MM/dd/yyyy a\\t h:mm tt}'}"/>
                        

Silverlight : The remote server returned an error: NotFound [Solution]

Tuesday, August 5, 2014 Category : , 0

System.Net.WebException: The remote server returned an error: NotFound

 

 

 

There are two places you have to edit:
1. edit the ServiceReferences.ClientConfig to accept a large buffer.
 <binding name="BasicHttpBinding_MosaicService" maxBufferSize="2147483647"
                    maxReceivedMessageSize="2147483647"> 
2. on the server in the web.config
 <system.serviceModel>
add a Httpbinding and name it
<bindings>
     <basicHttpBinding>
       <binding name="ServicesBinding" maxReceivedMessageSize="2000000" maxBufferSize="2000000">
         <readerQuotas maxArrayLength="2000000" maxStringContentLength="2000000"/>
    </binding>

which setts it to 2MB and  tell the service to use this binding
 <system.serviceModel>
    <services>
         <service behaviorConfiguration="TekPlayground.MosaicServiceBehavior"
    name="TekPlayground.MosaicService">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="ServicesBinding" contract="TekPlayground.MosaicService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
   </service>

 

Silverlight Datagrid Combobox Value Bind and get data

Saturday, April 12, 2014 Category : 0

1. Namespace for data grid           xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"


2.     <sdk:DataGrid Name="dataGrid"  AutoGenerateColumns="False" Width="650"
                                  ScrollViewer.VerticalScrollBarVisibility="Auto" Height="150" >
                        <sdk:DataGrid.Columns>

                            <sdk:DataGridTemplateColumn Header="Pay Mode" Width="100">
                                <sdk:DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <ComboBox  Name="cmbPayMode"
                                                  HorizontalAlignment="Left"
                                                  VerticalAlignment="Top" ItemsSource="{StaticResource oBillTypeList}"
                                                  DisplayMemberPath="CatName" SelectedValuePath="CatName"
                                                   SelectedItem="{Binding PayMode, Mode=TwoWay}"
                                                   SelectionChanged="cmbPayMode_SelectionChanged"
                                                  Width="80">
                                        </ComboBox>
                                    </DataTemplate>
                                </sdk:DataGridTemplateColumn.CellTemplate>
                            </sdk:DataGridTemplateColumn>


                           
                        </sdk:DataGrid.Columns>
                    </sdk:DataGrid>


3.   set data grid datasource by your desire datasource



  dataGrid.ItemsSource = oList;

4.  now for combobox data source in your class constructor , before initialize code add this code
            this.Resources.Add("oBillTypeList", oBillTypeList);
oBillTypeList  is a   ObservableCollection. other wise it cannnot load data from wcf ria service result set.

5.  to get data from your combobox or any control you can parse data from this code. or you can set bindmode two way.

foreach (AdvanceCollection p in oList)
                {
                    ComboBox cmbPayMod = dataGrid.Columns[0].GetCellContent(p) as ComboBox;
                    TextBox txtMode = dataGrid.Columns[2].GetCellContent(p) as TextBox;
                   
                }

Silverlight Image Upload Using WCF service

Wednesday, March 19, 2014 Category : 0

step 1 :  add a class in your web service project with following details

[DataContract]
    public class FilesUploader
    {

        [DataMember]
        public string FileName { get; set; }

        [DataMember]
        public string FoldersName { get; set; }

        [DataMember]
        public byte[] Imagestream { get; set; }


    public string Upload(FilesUploader image)
        {
            FileStream fileStream = null;
            BinaryWriter writer = null;
            try
            {
                //filePath = HttpContext.Current.Server.MapPath(".") + ConfigurationManager.AppSettings["PictureUploadDirectory"] + image.ImageName;
                string location = ConfigurationManager.AppSettings["imageFileLocation"].ToString();
                string strFilePath = location + image.FoldersName + "\\" + image.FileName;
            
                if (image.FileName != string.Empty)
                {
                    fileStream = File.Open(strFilePath, FileMode.Create);
                    writer = new BinaryWriter(fileStream);
                    writer.Write(image.Imagestream);
                }
                return OperatioinResult.Success;
            }
            catch (Exception ex)
            {
                return OperatioinResult.ERROR + " ~ " + ex.Message;
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
                if (writer != null)
                    writer.Close();
            }
        }


}


step 2 : add this method in your service operation contracnt 

 [OperationContract]
        public string FilesUploader_UploadFiles(FilesUploader fileByte)
        {
            //MemoryStream byFile = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(fileByte));
            return new FilesUploader().Upload(fileByte);
        }


Step 3 : use this service reference in your silverlight clinet project.

           OpenFileDialog op = new OpenFileDialog();
           op.Filter = "Images (*.jpg, *.png, *.bmp)|*.jpg;*.png;*.bmp";
            op.ShowDialog();
            if (op.File != null && op.File.Name != "")
            {
                    fileStram = (FileStream)op.File.OpenRead();
                    byte[] bytes = new byte[fileStram.Length];
                    fileStram.Read(bytes, 0, (int)fileStram.Length);

                    FilesUploader fUploader = new FilesUploader();
                    tempImage = "tempPatientImages" + op.File.Extension;
                    fUploader.FileName = tempImage;
                    fUploader.Imagestream = bytes;
                    fUploader.FoldersName = "PatientImges";

                    service.FilesUploader_UploadFilesAsync(fUploader);
                    // service is the object of service provider you need it chage it to your object name.
}

Silverlight Combobox (static / dynamic) value get set

Tuesday, March 18, 2014 Category : 0

Static Data combobox


                    <ComboBox Grid.Column="3"
                              Grid.Row="7"
                              Name="cmbMariedStaus"
                              HorizontalAlignment="Left"
                              VerticalAlignment="Top"
                              Style="{StaticResource ComboboxEntryStyle}">

                        <ComboBox.Items>
                            <ComboBoxItem>Married</ComboBoxItem>
                            <ComboBoxItem>Un married</ComboBoxItem>
                        </ComboBox.Items>
                    </ComboBox>


Value GET :   (cmb.SelectedItem as ComboBoxItem).Content.ToString();
Value Set :   cmb.SelectedItem = cmb.Items.SingleOrDefault(c => (c as ComboBoxItem).Content.ToString() == values);

Dyanamic Data Combobox

<ComboBox Grid.Column="1"
                              Grid.Row="9"
                              Name="cmbDepartment"
                              ItemsSource="{Binding}"
                              HorizontalAlignment="Left"
                              VerticalAlignment="Top"
                              DisplayMemberPath="DepName"
                              SelectedValuePath="DepID"
                              Style="{StaticResource ComboboxEntryStyle}">
                    </ComboBox>

Value GET : cmbDepartment.SelectedValue.ToString();

Vale Set : cmbDepartment.SelectedValue = "some value";

SQL server attach a series of database using query

Wednesday, February 19, 2014 Category : 0

1 . step one
save all attach database name of you pc sql server using following command.

SELECT * FROM sys.master_files

Save the result to excel sheet.

now if you re-install your pc OS.


use the following. query for resotre all database. you may need some tuning to your database depend on the data found.




declare @dbName nvarchar(max)
declare @dbpath nvarchar(max)

declare dbc cursor for


-- Note F1 condition is used for escap some database . no need to attach those db
-- Note F2 condition is used to load only mdf file

select db_name,path from tablesm where F1>9 and F2=1


open dbc

fetch next from dbc into @dbName,@dbpath

while @@fetch_status = 0

begin

declare @logs nvarchar(max)

-- Note generating log file location from mdf file.
set @logs = substring(@dbpath,0,len(@dbpath)-3) + '.LDF'
--print @logs

declare @SQL  nvarchar(max)

set @SQL ='
CREATE DATABASE '+@dbName+'
 ON
( FILENAME = '''+@dbpath+''' ),
( FILENAME = '''+@logs+''' )
 FOR ATTACH
 '
--print @SQL
exec( @SQL)

fetch next from dbc into @dbName,@dbpath

end

close dbc
deallocate dbc

Microsoft sql server error : 5123 [Solved]

Category : 0

Access denied Error Solution :

open the properties of ldf and mdf file
1.  Check the owner ship status of mdf and ldf file.
2. Check if there a use call  Everyone user added to file group , if not found then added it to and give full permission.










1. if you have a lot file to do this operation you can do it using command prompt.


for taking ownership of all database or file of a directorry

D:
cd D:\SOL ServerDatabase2008\All
pause
takeown /f . /r
pause

save it and give extension of bat file and then execute using admin previlage


for add everyone user of a direcotry

icacls * /t  /grant Everyone:F
pause

must run on same directory




Unable to load one or more of the requested types. (C#)

Thursday, January 16, 2014 Category : 0

System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

Error was found : when we are developing an application using .net framework 4, on visual 2010, using entity framework, it works perfectly on local or devlopement pc.

but in clinet side it's not working. and give the above error. after trying lot of things we are able to discover soltion
if we change the reference properties behavious which we use in our project. it work

so the solution is

select the follwoing references 


  • System.Data.Entity
  • System.Web.Entity
and change the property of copy local to True. build the solution now, and now you will get those reference dll in your bin. and now problem will solve.

System.ComponentModel.Win32Exception: Access is denied Error [Solved]

Wednesday, January 15, 2014 Category : 0

IIS ExternalException (0x80004005): Cannot execute a program. The command being executed was "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe 

Solution : Go to your application app pool . open advance settings. focus on Identity and then set your administrator privilege account. then restart app pool. and visit it again.


Powered by Blogger.